getattr on objects

Steve Holden sholden at holdenweb.com
Tue Oct 8 07:44:27 EDT 2002


"bromden" <bromden at gazeta.pl> wrote in message
news:3DA2B669.7070204 at gazeta.pl...
> 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)
>

I believe you'll need to override the __hasattr__() and similar special
methods. When you use the hasattr() function on an object the interpreter
framework ends up calling __hasattr__(). I don't have 1.5.2 around handily,
but I don't think *that* much has changed in 2.2:

>>> class C:
...   def __hasattr__(self, name): return 1
...   def __getattr__(self, name): return self.default
...   def default(self): return 'default'
...
>>> c = C()
>>> hasattr(c, "blah")
1
>>> c.hasattr("blah")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: default() takes exactly 1 argument (2 given)

Why you get this error is left as an exercise for the reader ;-)

>>> c.blah()
'default'
>>>

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------






More information about the Python-list mailing list