你不能
在Python中,类定义的工作方式如下。
解释器看到一条
class
语句,后跟一段代码。它创建一个新的名称空间并在该名称空间中执行该代码。
它
type
使用结果名称空间,类名,基类和元类(如果适用)调用内置函数。它将结果分配给类的名称。
在类定义中运行代码时,您不知道基类是什么,因此无法获取其属性。
您 可以 做的是在定义类后立即修改该类。
编辑:这是一个小类装饰器,您可以用来更新属性。想法是给它命名和一个函数。它遍历该类的所有基类,并使用该名称获取其属性。然后,它将使用从基类继承的值列表以及您在子类中定义的值来调用该函数。该调用的结果绑定到该名称。
代码可能更有意义:
>>> def inherit_attribute(name, f):... def decorator(cls):... old_value = getattr(cls, name)... new_value = f([getattr(base, name) for base in cls.__bases__], old_value)... setattr(cls, name, new_value)... return cls... return decorator... >>> def update_x(base_values, my_value):... return sum(base_values + [my_value], tuple())... >>> class Foo: x = (1,)... >>> @inherit_attribute('x', update_x)... class Bar(Foo): x = (2,)... >>> Bar.x(1, 2)这个想法是您定义
x为
(2,)in
Bar。然后,装饰器将遍历的子类
Bar,找到它们
x的所有s,然后
update_x与它们调用。因此它将调用
update_x([(1,)], (2,))
它通过连接它们来组合它们,然后将其重新绑定回去
x。那有意义吗?



