魔术方法

    xiaoxiao2025-05-24  14

    __setattr__

    __setattr__设置实例的属性存放在哪里,在init方法之后 例如:

    class A: d = {} def __init__(self,x,y): self.x = x self.y = y self.d['x'] = x self.d['y'] = y def __setattr__(self, key, value): self.d[key] = value #A类d字典里面放了一份 self.__dict__[key] = value #self实例的字典放了一份 def __getattr__(self, item): if item not in self.d.keys(): self.d[item] = 100 #设置默认值100 return self.d[item] #只让反回A类d字典的值 a = A(3,5) print(a.x) print(a.fgdf) print(a.__dict__) print(a.d) 打印信息: 3 100 {'x': 3, 'y': 5} {'x': 3, 'y': 5, 'fgdf': 100}

    __getattr__

    返回值控制对方想获取的信息,属性搜索顺序,self属性字典,类属性字典,父类属性,最后才由getattr返回值决定

    __getattribute__

    如果定义了次属性,属性的查找顺序先由__getattribute__的返回值开始

    最新回复(0)