getattr on objects

bromden bromden at gazeta.pl
Tue Oct 8 06:41:45 EDT 2002


I wanted to make a class which would pretend to have any
method you can call on it (returning some default value).
Defined a class:
 >>> class C:
...     def hasattr(self, name): return 1
...     def getattr(self, name): return self.default
...     def default(self): return 'default'

and its behaviour is:
 >>> c = C()
 >>> hasattr(c, 'bla')
0
 >>> c.hasattr('bla')
1

accordingly getattr(c, 'bla')() raises AttributeError
and c.getattr('bla')() returns 'default'

Is there a way to "override" hasattr (getattr) or
any other way to achieve the behaviour I described?
(I use python 1.5.2)

Regards,

Artur




More information about the Python-list mailing list