4 ms·
> for example, an innocent board[pos] access will look up __getitem__ in board.__dict__ and call the result Pedantic note: Special methods aren't looked up in
by Asooka 9y ago
> for example, an innocent board[pos] access will look up __getitem__ in board.__dict__ and call the result
Pedantic note: Special methods aren't looked up in __dict__, they're members of the C struct describing the type. "board[pos]" will look up the type of board, then call the tp_getitem function pointer in that struct. That can be a bit surprising to people:
class A:
def __getitem__(self, key):
print("A.__getitem__({})".format(key))
def foo(self, x):
print("A.foo({})".format(x))
a = A()
a["special"]
a.foo("ordinary")
a.__getitem__ = lambda key: print("Overriden __getitem__({})".format(key))
a.foo = lambda x: print("Overriden foo({})".format(x))
a["special"]
a.foo("ordinary")
Outputs:
A.__getitem__(special)
A.foo(ordinary)
A.__getitem__(special)
Overriden foo(ordinary)