How to mix-in __getattr__ after the fact?

dhyams dhyams at gmail.com
Fri Oct 28 13:34:35 EDT 2011


Python 2.7.2

I'm having trouble in a situation where I need to mix-in the
functionality of __getattr__ after the object has already been
created.  Here is a small sample script of the situation:

=============snip

import types

class Cow(object):
  pass
  # this __getattr__ works as advertised.
  #def __getattr__(self,a):
  #   print "CAUGHT INCLASS: Attempting to get attribute ",a


def attrgetter(self,a):
   print "CAUGHT: Attempting to get attribute ",a

bessie = Cow()

bessie.__getattr__ = types.MethodType(attrgetter,bessie,Cow)

# here, I should see my printout "attempting to get attribute"
# but I get an AttributeException
print bessie.milk
======================snip

If I call __getattr__ directly, as in bessie.__getattr__('foo'), it
works as it should obviously; so the method is bound and ready to be
called.  But Python does not seem to want to call __getattr__
appropriately if I mix it in after the object is already created.  Is
there a workaround, or am I doing something wrongly?

Thanks,



More information about the Python-list mailing list