Python:抽象类__init__ [英] Python: abstract class __init__
本文介绍了Python:抽象类__init__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用具有默认行为的构造函数声明抽象类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:抽象类__init__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文