Back
Featured image of post Python中__get__、__getattribute__、__getattr__拦截顺序

Python中__get__、__getattribute__、__getattr__拦截顺序

访问拦截顺序。

Python拦截顺序依次为:

  • 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
沪ICP备20004885号-2
jonathan.nuance@outlook.com
Built with Hugo
Theme Stack designed by Jimmy