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

Paul Moore p.f.moore at gmail.com
Tue Dec 6 13:59:48 EST 2011


On Dec 6, 5:29 pm, Matt Saxton <m... at scotweb.co.uk> wrote:
> 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'

I like that! I tend to think of metaclasses as for "complicated"
stuff. It's nice to see a simple use.
Paul



More information about the Python-list mailing list