【发布时间】:2020-04-23 10:51:51
【问题描述】:
我正在学习abc 模块并且想知道我想做的事情是否可行。
基本上,我为基类创建的每个孩子都应该拥有完全相同的__init__。基类将具有一些需要由子类定义的抽象属性。我会定义这些抽象属性,而不必每次都重写整个__init__。
例子:
我最初尝试过这样的事情
from abc import ABC,abstractmethod
class test(ABC):
def __init__(self):
pass
@property
@abstractmethod
def prop(self):
pass
class prop_ex(test):
@property
def prop(self):
return "THIS WORKS"
>>> from abc_tests import prop_ex
>>> blah = prop_ex()
>>> blah.prop
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'prop_ex' object has no attribute 'prop'
没用。
然后我尝试了
from abc import ABC,abstractmethod
class test(ABC):
def __init__(self):
self.prop = prop
@property
@abstractmethod
def prop(self):
pass
class prop_ex(test):
prop = "THIS WORKS"
@property
def prop(self):
return self._prop
测试
>>> from abc_tests import prop_ex
>>> blah = prop_ex()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "abc_tests.py", line 13, in __init__
self.prop = prop
NameError: name 'prop' is not defined
也不好,所以我尝试了
from abc import ABC,abstractmethod
class test(ABC):
def __init__(self):
pass
@property
@abstractmethod
def prop(self):
pass
class prop_ex(test):
self.prop = "THIS WORKS"
@property
def prop(self):
return self._prop
测试
>>> from dunder_tests import prop_ex
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "abc_tests.py", line 39, in <module>
class prop_ex(test):
File "abc_tests.py", line 40, in prop_ex
self.prop = "THIS WORKS"
NameError: name 'self' is not defined
对于最后一个,如果您在父级的__init__ 中设置断点并执行dir(self),您将在其中看到'prop'。
>>> blah = prop_ex()
> abc_tests.py(14)__init__()
-> self.prop = prop
(Pdb) dir(self)
['__abstractmethods__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', 'prop']
所以我认为这会奏效。
编辑:
我知道我完全把这个复杂化了。我本来可以做的
from abc import ABC,abstractmethod
class test(ABC):
def __init__(self):
pass
@property
@abstractmethod
def prop(self):
pass
class prop_ex(test):
prop = "THIS WORKS"
这样做有问题吗?
【问题讨论】:
标签: python python-3.x class abstract-class abc