derived classes and __getattr__

Peter Otten __peter__ at web.de
Fri Sep 5 10:47:13 CEST 2008


Alexandru Moșoi wrote:

> i'm facing the following problem:
> 
> class Base(object):
>   def __getattr__(self, attr): return lambda x: attr + '_' + x
> 
> def dec(callable):
>   return lambda *args: 'dec_' + callable(*args)
> 
> class Derived(Base):
>    what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
> what_so_ever
>    mumu = dec(Base.mumu)                          # wrong, base
> doesn't have mumu
> 
> any idea how to do this?

__getattr__() is defined in the class to create instance attributes on the
fly. If you want class attributes you have to put the __getattr__() method
into the class of the class, or "metaclass":

class Base(object):
    class __metaclass__(type):
        def __getattr__(self, attr):
            return lambda self, x: attr + '_' + x

def dec(callable):
    return lambda *args: 'dec_' + callable(*args)

class Derived(Base):
   what_so_ever = dec(Base.what_so_ever)

d = Derived()
print d.what_so_ever("42")

I don't see how you can turn this into something useful...

Peter



More information about the Python-list mailing list