I know that in Python it\'s possible to add at runtime a method to a class:
class Test:
def __init__(self):
self.a=5
test=Test()
import types
d
It's documented in Data model, section "Class Instances":
Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. If the class has a
__setattr__()
or__delattr__()
method, this is called instead of updating the instance dictionary directly.
So no matter if old-style or new-style, those two checks are always made on the type, rather then the instance.
See this section of the Python docs: Special method lookups for new-style classes
For new-style 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.
Follow the link for an elaboration of the rationale behind this. The basic idea as I understand it is that special methods that apply to both instance objects and type objects (such as __repr__
) need to be called consistently, rather than sometimes needing an explicit argument and sometimes receiving an implicit argument. By always calling the method on the type of the object, we know to always pass an explicit argument - but the side-effect is that the instance dictionary is bypassed.