【7.2】__getattr__、__getattribute__魔法函数

 1 #!/user/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __getattr__、__getattribute__
 4 # __getattr__ 就是在查找不到属性的时候调用
 5 # __getattribute__ 无条件进入__getattribute__
 6 from datetime import date
 7 
 8 
 9 class User:
10     def __init__(self, name, birthday, info={}):
11         self.name = name
12         self.birthday = birthday
13         self.info = info
14 
15     def __getattr__(self, item):
16         return self.info[item]
17 
18     # def __getattribute__(self, item):
19     #     return '__getattribute__'
20 
21 
22 if __name__ == '__main__':
23     user = User('zy', date(year=1998, month=6, day=8), {'company': 'imooc'})
24     print(user.company)
25     print(user.name)
imooc
zy

  

#!/user/bin/env python
# -*- coding:utf-8 -*-
# __getattr__、__getattribute__
# __getattr__ 就是在查找不到属性的时候调用
# __getattribute__ 无条件进入__getattribute__
from datetime import date


class User:
    def __init__(self, name, birthday, info={}):
        self.name = name
        self.birthday = birthday
        self.info = info

    def __getattr__(self, item):
        return self.info[item]

    def __getattribute__(self, item):
        return '__getattribute__'


if __name__ == '__main__':
    user = User('zy', date(year=1998, month=6, day=8), {'company': 'imooc'})
    print(user.company)
    print(user.name)
__getattribute__
__getattribute__

  

转载于:https://www.cnblogs.com/zydeboke/p/11259059.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值