What is the semantics meaning of 'object'?

Rotwang sg552 at hotmail.co.uk
Sun Jun 23 21:53:06 EDT 2013


On 23/06/2013 18:29, Steven D'Aprano wrote:
> On Sat, 22 Jun 2013 23:40:53 -0600, Ian Kelly wrote:
>> [...]
>>
>> Can you elaborate or provide a link?  I'm curious to know what other
>> reason there could be for magic methods to behave differently from
>> normal methods in this regard.
>
> It's an efficiency optimization. I don't quite get the details, but when
> you run something like "a + b", Python doesn't search for __add__ using
> the normal method lookup procedure. That allows it to skip checking the
> instance __dict__, as well as __getattribute__ and __getattr__.

It's not just an efficiency optimisation, it's actually necessary in 
cases where a dunder method gets called on a type. Consider what happens 
when one calls repr(int), for example - if this tried to call 
int.__repr__() by the normal lookup method, it would call the unbound 
__repr__ method of int with no self argument:

 >>> int.__repr__()
Traceback (most recent call last):
   File "<pyshell#1>", line 1, in <module>
     int.__repr__()
TypeError: descriptor '__repr__' of 'int' object needs an argument

By bypassing the instance-first lookup and going straight to the 
object's type's dictionary, repr(int) instead calls type.__repr__(int), 
which works:

 >>> type.__repr__(int)
"<class 'int'>"

This is explained here:

http://docs.python.org/3.3/reference/datamodel.html#special-lookup



More information about the Python-list mailing list