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

Matt Saxton matt at scotweb.co.uk
Tue Dec 6 12:29:45 EST 2011


On 06/12/11 15:57, Paul Moore wrote:
> 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

You can use a metaclass for this:

 >>> class BaseMeta(type):
...     def __new__(mcs, name, bases, dict):
...         dict['key'] = 'Key_for_%s' % name
...         return type.__new__(mcs, name, bases, dict)
...
 >>> class Base:
...     __metaclass__ = BaseMeta
...
 >>> class Inherited(Base):
...     pass
...
 >>> Base.key
'Key_for_Base'
 >>> Inherited.key
'Key_for_Inheritor'

You can find more info on metaclasses here:
http://http://docs.python.org/reference/datamodel.html#customizing-class-creation


Regards
Matt



More information about the Python-list mailing list