override at runtime __setattr__

后端 未结 2 1682
小蘑菇
小蘑菇 2021-01-18 15:55

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         


        
相关标签:
2条回答
  • 2021-01-18 16:15

    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.

    0 讨论(0)
  • 2021-01-18 16:17

    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.

    0 讨论(0)
提交回复
热议问题