目录python
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)
print(f1.__dict__ ) # 由于你重写了__setattr__,凡是赋值操做都会触发它的运行,你啥都没写,就是根本没赋值,除非你直接操做属性字典,不然永远没法赋值 f1.z = 3 print(f1.__dict__)
f1.__dict__['a'] = 3 # 咱们能够直接修改属性字典,来完成添加/修改属性的操做 del f1.a print(f1.__dict__)
----> from delattr {}
f1.xxxxxx
----> from getattr:你找的属性不存在