Python中__get__、__getattribute__、

2019-01-10  本文已影响0人  Nuance__

顺序依次为:

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
上一篇 下一篇

猜你喜欢

热点阅读