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

查看:31
本文介绍了如何在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.

注意:顺序很重要,你必须在@abstractmethod

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

Python 3.3+:(python文档):

from abc import ABC, abstractmethod

class C(ABC):
    @property
    @abstractmethod
    def my_abstract_property(self):
        ...

Python 2:(python 文档)

from abc import ABC, abstractproperty

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

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

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