changing __getattr__ dynamically
Satchidanand Haridas
sharidas at zeomega.com
Wed Jul 28 05:21:55 EDT 2004
Dan Bentley wrote:
>class foo(object):
> def __getattr__(self, name):
> return 42
>
>def e(self, name):
> return 2.7
>
>bar = foo()
>print bar.baz
>bar.__getattr__ = e
>print bar.baz
>
>I'd expect this to print:
>42
>2.7
>
>But instead it prints:
>42
>42
>
>Is there a way to change the actual __getattr__ used at runtime?
>
>-D"python 2.3.3 on Mac OS X 10.3.4"an
>
>
The following code will do so:
<code>
class foo(object):
def __getattr__(self, name):
if 'attrFunc' in self.__dict__:
return self.__dict__['attrFunc'](name)
else:
return 42
def __setattr__(self,name,value):
self.__dict__[name] = value
def e(self,name):
return 27
bar = foo()
print bar.baz
bar.attrFunc = bar.e
print bar.baz
</code>
Regards,
Satchit
----
Satchidanand Haridas (sharidas at zeomega dot com)
ZeOmega (www.zeomega.com)
Open Minds' Open Solutions
#20,Rajalakshmi Plaza,
South End Road,
Basavanagudi,
Bangalore-560 004, India
More information about the Python-list
mailing list