Quelques trucs avancés Python.
Savoir ça pourrait bien vous sauvez quelques heures de votre vie.
"For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary." → You cannot modify magic method directly from an instance, for instance, doing that wont work:
class C:
... pass
...
c = C()
c.len = lambda: 5
len(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()
"In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the getattribute() method even of the object’s metaclass:" → When a magic method is used and not called explicitely, then all special methods like getattribute are also bypassed.
For instance:
class Meta(type):
... def getattribute(args):
... print("Metaclass getattribute invoked")
... return type.getattribute(args)
...
class C(object, metaclass=Meta):
... def len(self):
... return 10
... def getattribute(args):
... print("Class getattribute invoked")
... return object.getattribute(args)
...
c = C()
c.len() # Explicit lookup via instance
Class getattribute invoked
10
type(c).len(c) # Explicit lookup via type
Metaclass getattribute invoked
10
len(c) # Implicit lookup
10