You can't.
A class definition works in Python works as follows.
The interpreter sees a class
statement followed by a block of code.
It creates a new namespace and executes that code in the namespace.
It calls the type
builtin with the resulting namespace, the class name, the base classes, and the metaclass (if applicable).
It assigns the result to the name of the class.
While running the code inside the class definition, you don't know what the base classes are, so you can't get their attributes.
What you can do is modify the class immediately after defining it.
EDIT: here's a little class decorator that you can use to update the attribute. The idea is that you give it a name and a function. It looks through all the base classes of your class, and gets their attributes with that name. Then it calls the function with the list of values inherited from the base class and the value you defined in the subclass. The result of this call is bound to the name.
Code might make more sense:
>>> 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)
The idea is that you define x
to be (2,)
in Bar
. The decorator will then go and look through the subclasses of Bar
, find all their x
s, and call update_x
with them. So it will call
update_x([(1,)], (2,))
It combines them by concatenating them, then binds that back to x
again. Does that make sense?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…