Consider these two classes:
class A(object):
name = "A"
class B(A):
name = "Child of " + A.name
Simple. A.name will be “A” and B.name will be “Child of A”.
But it seems wrong to hard code A.name into B‘s definition of name. I naturally want to write something like:
class B(A):
name = "Child of " + super(B).name
But that raises a NameError with B not yet being defined in the expression super(B). (Also, I’m not sure whether it should/would be super(B) or super(B, B) or something else, but that’s a moot point given the NameError.)
What’s the right way to do this, i.e. use super in the definition of a class attribute?
It can’t be done inside the class definition, for the reason you discovered: inside the class definition, you don’t have access to the class itself, since it’s not defined yet.
You can do it with a class decorator, though (if you’re using a version of Python with class decorators, which I think is 2.6 and up):