How to deal __getattr__

L

limodou

I found it puzzled me that:

class A:
def __getattr__(self, name):
return None
a=A()
b=A()
a==b will raise Exception:

__eq__

Traceback (most recent call last):
File "<pyshell#7>", line 1, in -toplevel-
a==b
TypeError: 'NoneType' object is not callable

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__?

Thankx
 
A

Andrew Dalke

limodou said:
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

a.__eq__(b)

if that fails it tries the three-way comparison

a.__cmp__(b)

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.

Andrew
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top