在下面的代码中,我创建了一个基本抽象类Base
。我想要继承自的所有类Base
提供name
财产,所以我把这个财产@abstractmethod
.
然后我创建了一个子类Base
,称为Base_1
,它旨在提供一些功能,但仍然保持抽象。没有name
财产在Base_1
,但是 python 会毫无错误地实例化该类的对象。如何创建抽象属性?
from abc import ABCMeta, abstractmethod
class Base(object):
# class Base(metaclass = ABCMeta): <- Python 3
__metaclass__ = ABCMeta
def __init__(self, str_dir_config):
self.str_dir_config = str_dir_config
@abstractmethod
def _do_stuff(self, signals):
pass
@property
@abstractmethod
def name(self):
"""This property will be supplied by the inheriting classes
individually.
"""
pass
class Base1(Base):
__metaclass__ = ABCMeta
"""This class does not provide the name property and should
raise an error.
"""
def __init__(self, str_dir_config):
super(Base1, self).__init__(str_dir_config)
# super().__init__(str_dir_config) <- Python 3
def _do_stuff(self, signals):
print "Base_1 does stuff"
# print("Base_1 does stuff") <- Python 3
class C(Base1):
@property
def name(self):
return "class C"
if __name__ == "__main__":
b1 = Base1("abc")
Since Python 3.3修复了一个错误,这意味着property()
当应用于抽象方法时,装饰器现在可以正确识别为抽象。
注意:顺序很重要,您必须使用@property
above @abstractmethod
Python 3.3+: (蟒蛇文档):
from abc import ABC, abstractmethod
class C(ABC):
@property
@abstractmethod
def my_abstract_property(self):
...
Python 2: (蟒蛇文档)
from abc import ABCMeta, abstractproperty
class C:
__metaclass__ = ABCMeta
@abstractproperty
def my_abstract_property(self):
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)