如何在python抽象类中创建抽象属性 [英] How to create abstract properties in python abstract classes

查看:482
本文介绍了如何在python抽象类中创建抽象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我创建一个基本抽象类 Base 。我希望从 Base 继承的所有类都提供 name 属性,因此我将此属性设置为 @abstractmethod

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.

然后我创建了 Base 的子类。 Base_1 ,旨在提供某些功能,但仍保持抽象。 Base_1 中没有 name 属性,但是python实例化了该类的对象而没有错误。如何创建抽象属性?

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')  


推荐答案

Python 3.3 以来,已修复一个错误意味着 property()装饰器现在可以正确地识别为抽象,应用于抽象方法。

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文档

class C(ABC):
    @abstractproperty
    def my_abstract_property(self):
        ...

这篇关于如何在python抽象类中创建抽象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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