python访问实例属性x_类实例属性的设置与访问

>>> class T:

def __init__(self, obj):

self.obj = obj # 这里也会调用 __setattr__ 方法

def __getattr__(self, name):

try:

return self.obj[name] # 以 obj 中的值来代替

except KeyError:

raise AttributeError("'T' object has no attribute '%s'" %name)

def __getattribute__(self, name):

return super().__getattribute__(name) # 避免无穷递归

def __setattr__(self, name, value):

print('setting attribute', name)

if name != 'obj' and not isinstance(value, int): # “obj”属性不是整数,需要排除

raise TypeError("value need to be an integer.")

super().__setattr__(name, value) # 避免无穷递归

运行结果:

>>> t = T({'key': 'vvv', 'aa': 'b'})

setting attribute obj

>>>

>>> t.__dict__

{'obj': {'key': 'vvv', 'aa': 'b'}}

>>> t.a # 这里因为属性“a”也不在属性“obj”中

Traceback (most recent call last):

File "", line 6, in __getattr__

return self.obj[name]

KeyError: 'a'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "", line 1, in

t.a

File "", line 8, in __getattr__

raise AttributeError("'T' object has no attribute '%s'" %name)

AttributeError: 'T' object has no attribute 'a'

>>> t.aa # aa 在 obj 中

'b'

>>> t.x = 'aaa'

setting attribute x

Traceback (most recent call last):

File "", line 1, in

t.x = 'aaa'

File "", line 11, in __setattr__

raise TypeError("value need to be an integer.")

TypeError: value need to be an integer.

>>>

>>> t.x = 13

setting attribute x

>>>

>>> t.__dict__

{'obj': {'key': 'vvv', 'aa': 'b'}, 'x': 13}

>>>

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2017-07-31 10:48

浏览 116

评论

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值