python - Implementing __getitem__ in new-style classes -
i have 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 works fine:
a = a() a[0]
but not:
b = b() b[0]
raising typeerror.
i found new-style classes magic methods in class __dict__ instead of instance __dict__ . right? why so? know article explaining ideas behind? tried rtfm, maybe not right ones or did not catch thing...
thank much! paul
this documented in python datamodel documentation: special method lookup new-style classes:
for new-style classes, implicit invocations of special methods guaranteed work correctly if defined on object’s type, not in object’s instance dictionary.
and
the rationale behind behaviour lies number of special methods such
__hash__()
,__repr__()
implemented objects, including type objects. if implicit lookup of these methods used conventional lookup process, fail when invoked on type object itself[.]
so, because both hash(int)
and hash(1)
must work, special methods looked on type instead of on instance. if __hash__()
looked straight on object, hash(int)
translated int.__hash__()
, , fail, because int.__hash__()
unbound method , expects called on actual instance of int()
(e.g. 1
); hash(int)
, type.__hash__()
should called instead:
>>> hash(1) == int.__hash__(1) true >>> hash(int) == type.__hash__(int) true >>> int.__hash__() traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: descriptor '__hash__' of 'int' object needs argument
this backwards-incompatible change, applies new-style objects.
Comments
Post a Comment