I will try to summarize what is said in the excerpt, and, in particular, the part in bold. Generally speaking, when Python tries to find the value of the attribute (including the method), it first checks the instance (i.e., the actual object you created), and then the class. The code below illustrates the general behavior.
class MyClass(object): def a(self): print("howdy from the class") n = MyClass()
What part of fatty conditions is that this behavior does not apply to “special methods” such as __getitem__ . In other words, overriding __getitem__ at the instance level ( n.__getitem__ = fake_get_item in your example) does nothing: when a method is called via n[] syntax, an error occurs because the class does not implement this method. (If the general behavior was also carried out in this case, the result of print(n[23]) would be to print 23, that is, Execute the fake_get_item method).
Another example of the same behavior:
class MyClass(object): def __getitem__(self, idx): return idx n = MyClass() fake_get_item = lambda x: "fake" print(fake_get_item(23))
In this example, instead of the instance binding method, the class method for __getitem__ (which returns the index number) (which returns 'fake' ) is called.
pills source share