override at runtime __setattr__

后端 未结 2 1683
小蘑菇
小蘑菇 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.

提交回复
热议问题