首页 > 编程语言 > 详细

Python3.7.5中__get__、__getattribute__、__getattr__拦截顺序

时间:2019-12-31 15:48:38      阅读:175      评论:0      收藏:0      [点我收藏+]
  • 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

    原文链接:https://www.jianshu.com/p/4e34c9b2fdc3

Python3.7.5中__get__、__getattribute__、__getattr__拦截顺序

原文:https://www.cnblogs.com/yimai-series/p/12124734.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!