抽象基础 class 中的断言?

Assertion in abstract base class?

本质上我想要的是要求抽象基础classes的子classes不仅实现某些属性或方法,而且还可以对它们提出要求,例如数据类型或允许的值。

例如,假设我想要求 class 具有 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

Where/how 我会在基础 class 中声明这个吗?

使用 __init_subclass__ 对 class 属性实施限制。

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