如何在 Python 中定义抽象类的构造函数实现? [英] How define constructor implementation for an Abstract Class in Python?

查看:27
本文介绍了如何在 Python 中定义抽象类的构造函数实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图声明一个抽象类 A 带有默认行为的构造函数:所有子类都必须初始化一个成员 self.n:

I am trying to declare an abstract class A with a constructor with a default behavior: all subclasses must initialize a member self.n:

from abc import ABCMeta

class A(object):
    __metaclass__ = ABCMeta

    def __init__(self, n):
        self.n = n

然而,我不想让 A 类被实例化,因为它是一个抽象类.问题是,这实际上是允许的:

However, I do not want to let the A class be instantiated because, well, it is an abstract class. The problem is, this is actually allowed:

a = A(3)

这不会产生任何错误,而我希望它应该这样做.

This produces no errors, when I would expect it should.

那么:如何在为构造函数定义默认行为的同时定义一个不可实例化的抽象类?

So: how can I define an un-instantiable abstract class while defining a default behavior for the constructor?

推荐答案

使 __init__ 成为抽象方法:

from abc import ABCMeta, abstractmethod

class A(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self, n):
        self.n = n


if __name__ == '__main__':
    a = A(3)

帮助:

TypeError: Can't instantiate abstract class A with abstract methods __init__

Python 3 版本:

Python 3 version:

from abc import ABCMeta, abstractmethod

class A(object, metaclass=ABCMeta):

    @abstractmethod
    def __init__(self, n):
        self.n = n


if __name__ == '__main__':
    a = A(3)

同样有效:

TypeError: Can't instantiate abstract class A with abstract methods __init__

这篇关于如何在 Python 中定义抽象类的构造函数实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆