I have this code:
class A:
def __init__(self):
def method(self, item):
print self, ": Getting item", item
self.__getitem__ = types.MethodType(method, self, self.__class__)
class B(object):
def __init__(self):
def method(self, item):
print self, ": Getting item", item
self.__getitem__ = types.MethodType(method, self, self.__class__)
Then this works fine:
a = A()
a[0]
But this does not:
b = B()
b[0]
raising TypeError.
I found that new-style classes look for magic methods in class __dict__ instead of instance __dict__ . Is this right? Why is it so? Do you know about any article explaining the ideas behind? I tried RTFM, but maybe not the right ones or did not catch the thing…
Thank you very much!
Paul
This is documented in the Python datamodel documentation: Special method lookup for new-style classes:
and
So, because both
hash(int)andhash(1)must work, special methods are looked up on the type instead of on the instance. If__hash__()was looked up straight on the object,hash(int)would be translated toint.__hash__(), and that would fail, becauseint.__hash__()is an unbound method and it expects to be called on an actual instance ofint()(e.g.1); so forhash(int),type.__hash__()should called instead:This is a backwards-incompatible change, so it only applies to new-style objects.