1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# -*- coding: utf-8 -*- """ @Time: 2018/4/30 @Author: songhao @微信公众号: zeropython @File: demo_getattr.py """ """ getattr, getattrubute getattr 在查找不到属性的时候调用 class User: def __init__(self,name): self.name =name def __getattr__(self, item): return ("not find atter") if __name__ == '__main__': user= User("songhao") print(user.age) print(user.name) 输出结果 # not find atter # songhao class User: def __init__(self, name, info={}): self.name = name self.info = info def __getattr__(self, item): return self.info[item] if __name__ == '__main__': user = User("songhao",info={"weixin":"zeropython"}) print(user.weixin) 输出: # zeropython class User: def __init__(self, name, info={}): self.name = name self.info = info def __getattr__(self, item): return self.info[item] def __getattribute__(self, item): # 调用属性最优先调用这个属性 return "hello world" if __name__ == '__main__': user = User("songhao",info={"weixin":"zeropython"}) print(user.weixin) 输出: #hello world |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Student(object): def __init__(self): self.name = 'Michael' def __getattr__(self, attr): if attr=='score': return 99 if attr=='age': return lambda: 25 raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr) s = Student() print(s.name) print(s.score) print(s.age()) # AttributeError: 'Student' object has no attribute 'grade' print(s.grade) |
有更高追求的建议读读源码
https://github.com/michaelliao/sinaweibopy/blob/master/weibo.py#L307
参考:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319098638265527beb24f7840aa97de564ccc7f20f6000
