getattr on objects

Bjarke Dahl Ebert bebert at worldonline.dk
Tue Oct 8 07:57:18 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'

Try this:
class C:
    def __getattr__(self, name): return self.default()
    def default(self): return 'default'

When I wonder how Python communicates with objects (e.g., What is the effect
of "foo in myobj"), I just try with a little piece of code:

class Foo:
    def __getattr__(self, name):
        print name
        raise AttributeError

Now, evaluating "1 in Foo()", reveals the things that Python tries, in order
(version 2.2.1):
__contains__
__iter__
__getitem__
which makes pretty good sense :-)

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

Hm.. I use 2.2.1, but I don't think this has changed since 1.5.2.
hasattr uses the getattr protocol, so you cannot override hasattr without
"calculating" the attribute when asked, in __getattr__.
So, for objects that does heavy on-the-fly calculation of attributes, it is
better to access them with:
    try: foo = bar.hello
    except AttributeError: # ...
than
    if hasattr(bar, "hello"):
        foo = bar.hello
        # ...
    else: # ...


Kind regards,
Bjarke







More information about the Python-list mailing list