python __setattr__ , __getattr__ , __setattribute__ 防止死循环

Python Class 对象或类型通过内置成员 __dict__ 来存储成员信息。

  我们还可以通过重载 __getattr__ 和 __setattr__ 来拦截对成员的访问,需要注意的是 __getattr__ 只有在访问不存在的成员时才会被调用。

>>> class Class1:
  def __getattr__(self, name):
    print "__getattr__"
    return None
  def __setattr__(self, name, value):
    print "__setattr__"
    self.__dict__[name] = value
    
>>> a = Class1()
>>> a.x
__getattr__
>>> a.x = 123
__setattr__
>>> a.x
123

  如果类型继承自 object,我们可以使用 __getattribute__ 来拦截所有(包括不存在的成员)的获取操作。

  注意在 __getattribute__ 中不要使用 "return self.__dict__[name]" 来返回结果,因为在访问 "self.__dict__" 时同样会被 __getattribute__ 拦截,从而造成无限递归形成死循环。

>>> class Class1(object):
  def __getattribute__(self, name):
    print "__getattribute__"
    return object.__getattribute__(self, name)
  
>>> a = Class1()
>>> a.x
__getattribute__
Traceback (most recent call last):
 File "<pyshell#3>", line 1, in <module>
 a.x
 File "<pyshell#1>", line 4, in __getattribute__
 return object.__getattribute__(self, name)
AttributeError: 'Class1' object has no attribute 'x'
>>> a.x = 123
>>> a.x
__getattribute__
123

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值