Python __getattr__ __getattribute__

来源:互联网 发布:qt保存数据到文件 编辑:程序博客网 时间:2024/06/05 02:11

当调用对象属性时, Python会自动调用 getattribute, 当getattribute找不到属性时 会调用getattr
比如 a.dict 相当于执行了 a.getattribute(‘dict‘) 如果我们在重载getattribute中又调用dict的话,会无限递归
`class C(object):
def setattr(self, name, value):
print “setattr called:”, name, value
object.setattr(self, name, value)

def __getattr__(self, name):      print "__getattr__ called:", name  def __getattribute__(self, name):      print "__getattribute__ called:",name      return object.__getattribute__(self, name)  

c = C()
c.x = “foo”`

0 0