python如何定义抽象类,如何在python抽象类中创建抽象属性

In the following code, I create a base abstract class Base. I want all the classes that inherit from Base to provide the name property, so I made this property an @abstractmethod.

Then I created a subclass of Base, called Base_1, which is meant to supply some functionality, but still remain abstract. There is no name property in Base_1, but nevertheless python instatinates an object of that class without an error. How does one create abstract properties?

from abc import ABCMeta, abstractmethod

class Base(object):

__metaclass__ = ABCMeta

def __init__(self, strDirConfig):

self.strDirConfig = strDirConfig

@abstractmethod

def _doStuff(self, signals):

pass

@property

@abstractmethod

def name(self):

#this property will be supplied by the inheriting classes

#individually

pass

class Base_1(Base):

__metaclass__ = ABCMeta

# this class does not provide the name property, should raise an error

def __init__(self, strDirConfig):

super(Base_1, self).__init__(strDirConfig)

def _doStuff(self, signals):

print 'Base_1 does stuff'

class C(Base_1):

@property

def name(self):

return 'class C'

if __name__ == '__main__':

b1 = Base_1('abc')

解决方案

Since Python 3.3 a bug was fixed meaning the property() decorator is now correctly identified as abstract when applied to an abstract method.

Note: Order matters, you have to use @property before @abstractmethod

Python 3.3+: (python docs):

class C(ABC):

@property

@abstractmethod

def my_abstract_property(self):

...

Python 2: (python docs)

class C(ABC):

@abstractproperty

def my_abstract_property(self):

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值