__setattr__,__delattr__,__getattr__

table of Contents

class Foo:
    x = 1

    def __init__(self, y):
        self.y = y

    def __getattr__(self, item):
        print('----> from getattr:你找的属性不存在')

    def __setattr__(self, key, value):
        print('----> from setattr')
        # self.key = value  # 这就无限递归了,你好好想想
        # self.__dict__[key] = value  # 应该使用它

    def __delattr__(self, item):
        print('----> from delattr')
        # del self.item  # 无限递归了
        self.__dict__.pop(item)


f1 = Foo(10)

__setattr__

  • Add / modify attributes will trigger its execution
print(f1.__dict__
      )  # 因为你重写了__setattr__,凡是赋值操作都会触发它的运行,你啥都没写,就是根本没赋值,除非你直接操作属性字典,否则永远无法赋值
f1.z = 3
print(f1.__dict__)

__delattr__

  • Delete property when the trigger
f1.__dict__['a'] = 3  # 我们可以直接修改属性字典,来完成添加/修改属性的操作
del f1.a
print(f1.__dict__)
----> from delattr
{}

__getattr__

  • Only call the property at the point of use and the property does not exist when will trigger
f1.xxxxxx
----> from getattr:你找的属性不存在

Guess you like

Origin www.cnblogs.com/nickchen121/p/10991163.html