你可以定义一个__init_subclass__
的方法Parent
初始化的类Child.__props__
。每次 of 的子类时都会调用此方法Parent
已创建,我们可以使用它来修改__props__
该类继承了一个可选的__props__
参数作为类定义的一部分传递。
class Parent:
__props__ = (('a', str, 'a var'), ('b', int, 'b var'))
def __init_subclass__(cls, __props__=(), **kwargs):
super().__init_subclass__(**kwargs)
cls.__props__ = cls.__props__ + __props__
class Child(Parent, __props__=(('c', str, 'foo'),)):
pass
print(Child.__props__)
# (('a', <class 'str'>, 'a var'), ('b', <class 'int'>, 'b var'), ('c', <class 'str'>, 'foo'))
class GrandChild(Child, __props__=(('d', float, 'd var'),)):
pass
print(GrandChild.__props__)
# (('a', <class 'str'>, 'a var'), ('b', <class 'int'>, 'b var'),
# ('c', <class 'str'>, 'foo'), ('d', <class 'float'>, 'd var'))