是否存在用于派生类定义的抽象基类(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+中的类变量实现类似的功能?
答案 0 :(得分:0)
使用自定义元类:
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>