__getattr__ Confusion

Peter Otten __peter__ at web.de
Mon Feb 4 09:15:47 EST 2013


Saul Spatz wrote:

> Now I have another question.  If dunder methods are looked up only in the
> class, not the instance, why did defining __nonzero__ the way I did work? 
> Shouldn't I have had to define it with a def?  Is __nonzero__ a special
> case?

Unfortunately the situation is a bit more complex. Classic classes (like 
Tkinter.Frame) behave differently from newstyle classes (subclasses of 
object):

>>> def nz():
...     print "nonzero"
...     return 0
... 
>>> class Classic: pass
... 
>>> c = Classic()
>>> c.__nonzero__ = nz
>>> not c
nonzero
True
>>> class New(object): pass
... 
>>> n = New()
>>> n.__nonzero__ = nz
>>> not n
False

So Steven is wrong here.

> Shouldn't I have had to define it with a def?

If you mean as opposed to a lambda, there is no difference between

f = lambda ...

and

def f(...): ...

other than that the last one gives you a nice name in a traceback.




More information about the Python-list mailing list