Referring to the class name from a class variable where inheritance is involved
Ian Kelly
ian.g.kelly at gmail.com
Tue Dec 6 13:12:14 EST 2011
On Tue, Dec 6, 2011 at 8:57 AM, Paul Moore <p.f.moore at gmail.com> 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?
How about a class property?
class classproperty(object):
def __init__(self, fget):
self.__fget = fget
def __get__(self, instance, owner):
return self.__fget(owner)
class BaseClass(object):
@classproperty
def key(cls):
return "Key_for_" + cls.__name__
class DerivedClass(BaseClass):
pass
assert BaseClass.key == BaseClass().key == "Key_for_BaseClass"
assert DerivedClass.key == DerivedClass().key == "Key_for_DerivedClass"
If you like, you can also expand classproperty to allow setters and
deleters like property does.
Cheers,
Ian
More information about the Python-list
mailing list