I have a class Klass with a class attribute my_list. I have a subclass of it SubKlass, in which i want to have a class attribute my_list which is a modified version of the same attribute from parent class:
class Klass():
my_list = [1, 2, 3]
class SubKlass(Klass):
my_list = Klass.my_list + [4, 5] # this works, but i must specify parent class explicitly
#my_list = super().my_list + [4, 5] # SystemError: super(): __class__ cell not found
#my_list = my_list + [4, 5] # NameError: name 'my_list' is not defined
print(Klass.my_list)
print(SubKlass.my_list)
So, is there a way to access parent class attribute without specifying its name?
UPDATE:
There is a bug on Python issue tracker: http://bugs.python.org/issue11339 . Let’s hope it will be solved at some point.
You can’t.
A class definition works in Python works as follows.
The interpreter sees a
classstatement followed by a block of code.It creates a new namespace and executes that code in the namespace.
It calls the
typebuiltin 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:
The idea is that you define
xto be(2,)inBar. The decorator will then go and look through the subclasses ofBar, find all theirxs, and callupdate_xwith them. So it will callIt combines them by concatenating them, then binds that back to
xagain. Does that make sense?