changing __getattr__ dynamically

Peter Otten __peter__ at web.de
Wed Jul 28 05:49:09 EDT 2004


Dan Bentley wrote:

> Is there a way to change the actual __getattr__ used at runtime?

Special methods are always looked up in the class, any changes must
therefore be made in the class and will affect all instances.

>>> class foo(object):
...     def __getattr__(self, name):
...             return 42
...
>>> def e(self, name):
...     return 2.7
...
>>> bar = foo()
>>> print bar.baz
42
>>> bar.__class__.__getattr__ = e
>>> print bar.baz
2.7

Peter




More information about the Python-list mailing list