基本上,我想要的是要求抽象基类的子类不仅实现某些属性或方法,而且还可以对这些属性或方法提出要求,例如数据类型或允许的值。
例如,假设我要要求一个具有name
并且该name
以字母'a'开头的类:
from abc import ABC, abstractproperty
class Base(ABC):
@abstractproperty
def name(self):
assert self.name[0] == 'a' # or similar; help needed here
class Derived1(Base):
name = 'albert' # I want this class definition to work
class Derived2(Base):
name = 'john' # I want this class definition to fail the 'a' assertion
我在哪里/如何在基类中断言?
答案 0 :(得分:4)
使用__init_subclass__
来强制限制类属性。
class Base:
def __init_subclass__(cls):
try:
name = cls.name
except AttributeError:
raise ValueError("No name attribute")
if name[0] != "a":
raise ValueError("first letter of name is not 'a'")
class Derived1(Base):
name = 'albert' # OK
class Derived2(Base):
name = 'john' # Fails due to first letter 'j'
# Fails because Derived3.name is never defined
class Derived3(Base):
pass