Friday, 15 May 2015

python - Very strange behavior of operator 'is' with methods -



python - Very strange behavior of operator 'is' with methods -

why first result false, should not true?

>>> collections import ordereddict >>> ordereddict.__repr__ ordereddict.__repr__ false >>> dict.__repr__ dict.__repr__ true

for user-defined functions, in python 2 unbound , bound methods created on demand, through descriptor protocol; ordereddict.__repr__ such method object, wrapped function implemented pure-python function.

the descriptor protocol phone call __get__ method on objects back upwards it, __repr__.__get__() called whenever seek access ordereddict.__repr__; classes none (no instance) , class object passed in. because new method object each time function __get__ method invoked, is fails. not same method object.

dict.__repr__ not custom python function c function, , __get__ descriptor method essentially returns self when accessed on class. accessing attribute gives same object each time, is works:

>>> dict.__repr__.__get__(none, dict) dict.__repr__ # none means no instance true

methods have __func__ attribute referencing wrapped function, utilize test identity:

>>> ordereddict.__repr__ <unbound method ordereddict.__repr__> >>> ordereddict.__repr__.__func__ <function __repr__ @ 0x102c2f1b8> >>> ordereddict.__repr__.__func__.__get__(none, ordereddict) <unbound method ordereddict.__repr__> >>> ordereddict.__repr__.__func__ ordereddict.__repr__.__func__ true

python 3 away unbound methods, function.__get__(none, classobj) returns function object (so behaves dict.__repr__ does). see same behaviour bound methods, methods retrieved instance.

python python-2.7 methods python-internals

No comments:

Post a Comment