Referring to the class name from a class variable where inheritance is involved

Paul Moore p.f.moore at gmail.com
Tue Dec 6 10:57:25 EST 2011


I want to set up an inheritance hierarchy. The base class will define
a string value which should include the class name, but I don't want
people who inherit from my class to have to remember to override the
value.

If I do this using an instance variable, it's reasonably easy:

>>> class Base:
...     def __init__(self):
...         self.key = 'Key_for_' + self.__class__.__name__
...     def display(self):
...         print self.key
...
>>> class Inherited(Base):
...     pass
...
>>> b = Base()
>>> i = Inherited()
>>> b.display()
Key_for_Base
>>> i.display()
Key_for_Inherited

Rather than having the key for every instance, I'd like to use a class
variable, but I can't see how I'd make that work (a class variable
which is inherited but has a different value in derived classes). I
could use a classmethod,but that feels like even more overkill than an
instance attribute.

Is there a way of doing this via class variables or something, or more
relevantly, I guess, what would be the idiomatic way of doing
something like this?

Thanks,
Paul



More information about the Python-list mailing list