How to deal __getattr__

Andrew Dalke adalke at
Sat Oct 16 10:21:01 CEST 2004

limodou wrote:
> I want to compare the objects themself not the attributes of them. But
> it seems python invoke __getattr__ method, it's strange. How can I
> compare the object directly without calling __getattr__?

You need to know a bit more about Python's object model.

In Python, attributes and methods are fetched with the
same notation, using the dot, as "a.z"

If it's a function then doing a.z returns a "bound method".
That means it knows it's a method of the specific instance
a.  That's how a.z() gets passed 'a' as the "self" parameter.

When you ask for a == b Python does the following steps.
(It's slightly more complicated and a bit different,
if you had used new-style classes derived from "object".)

First see if a rich comparison is defined


if that fails it tries the three-way comparison


if that fails it uses the result of

   id(a) == id(b)

See the first step?  That gets the '__eq__' property
of the instance a.  Because Python doesn't distinguish
at this level between attributes and methods it first
looks for the instance in a.__dict__.  That fails so
it uses the backup plan of calling __getattr__.  In
you case it succeeds and returns None.

So "a.__eq__" returns None for you.  The next step is
to call None(b) .  But that doesn't work because None
is not a callable object.

An exception is raised and that's why you see that
error message.

				dalke at

More information about the Python-list mailing list