python __setattr__ __getattr__
作者:互联网
class A: def __init__(self,width,heigth): self.width = width self.heigth = heigth def __setattr__(self,name, value): print("----set %s attribute" %name) if name == "size": print("controll sieze attribute") self.width = value # print(self.width) else: self.__dict__[name] = value def __getattr__(self,name): print("---get %s attribute " %name) a = A(3,4) a.size = 100 print(a.width) print(a.__dict__)
----set width attribute ----set heigth attribute ----set size attribute controll sieze attribute ----set width attribute 100 请按任意键继续. . .
__getattribute__(self, name) : 当程序访问对象的name属性时会自动调用
__getattr__(self,name) : 当程序访问对象的name属性且改属性不存在时被自动调用
__setattr__(self,name): 当程序对对象的name属性赋值的时候被自动调用
__delattr__(self, name) :当程序删除对象的name属性的时候被自动调用
标签:__,name,python,attribute,self,width,getattr,print 来源: https://www.cnblogs.com/shunguo/p/15706160.html