顺序依次为:
- get 仅在作为类属性的值且被访问时,经过此函数
- getattribute
- 已存在的属性
- 若不存在属性getattr
class Account(object):
def __get__(self, instance, owner):
print('作为别人小弟(类属性)被访问时,无条件经过我')
return self
def __getattribute__(self, item):
print('访问属性时,无条件经过我')
return object.__getattribute__(self, item)
name = 'xiaomi'
def __getattr__(self, item):
print('我只负责捡漏')
if item == 'product':
return 'cellphone'
class User:
name = 'Lucy'
account = Account()
if __name__ == '__main__':
u = User()
p = u.account.product
print(p)
## Output:
## 作为别人小弟(类属性)被访问时,无条件经过我(u.account触发)
## 访问属性时,无条件经过我(u.account.product触发)
## 我只负责捡漏(u.account.product触发)
## cellphone
网友评论