繁体   English   中英

如何在抽象基类(Python 3+)中创建我希望派生类定义的类级属性?

[英]How do I create a class level property in an abstract base class (Python 3+) that I want derived classes to define?

是否有一种在抽象基类(ABC)中创建类级变量的标准方法,我们希望派生类定义?

我可以用以下属性实现它:

from abc import ABC
from abc import abstractmethod

class Parent(ABC):
    @property
    @abstractmethod
    def provider(self) -> str:
        """The provider that the payload generator is applicable for"""
        raise NotImplementedError()

class Child(Parent):
    @property
    def provider(self) -> str:
        return 'some provider'

但是属性链接到实例而不是类。 有没有办法可以在Python 3.6+中为类变量实现类似的功能?

使用自定义元类:

class RequireProperty(type):

    _required = ['define_me']

    def __new__(cls, name, bases, attributes):

        new_class = super().__new__(cls, name, bases, attributes)
        if not all(required_attribute in attributes for required_attribute in cls._required):
            raise TypeError

        else:
            return new_class

如果您没有定义属性:

class DidntDefine(metaclass=RequireProperty):
    pass

DidntDefine()

输出:

TypeError: You must define all of ['define_me'].

如果你这样做:

class DidDefine(metaclass=RequireProperty):

    define_me = None

DidDefine()

输出:

<__main__.DidDefine at 0x2bcec632198>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM