作者:麦叔
来源:麦叔编程
AttributeError这是某位麦友提的问题:
❝
麦叔之前有讲过python的 __call__(),__get__, __getattr__, __getattribute__这几个方法吗,网上搜索的讲的都不透彻,烦请麦叔讲解下吧
❞
这几个函数用途差别还是挺大的。之前我们讨论了__call__。今天我们来聊一下__getattr__。
直接看例子吧:
class Maiyou(): def __init__(self,name, age): self.name=name self.age=agem1 = Maiyou('Kevin', 18)print(m1.name)print(m1.age)print(m1.gender)打印结果:
Kevin18Traceback (most recent call last): File "/Users/maishu/git/wx_maishucode/code/078.py", line 9, in <module> print(m1.gender)AttributeError: 'Maiyou' object has no attribute 'gender'打印gender的时候报了AttributeError错误,因为Maiyou类根本没有gender这个属性。
__getattr__来拯救直接上答案,稍后再解释:
class Maiyou(): def __init__(self,name, age): self.name=name self.age=age def __getattr__(self, item): self.__dict__[item]='不知道' return '不知道' m1 = Maiyou('Kevin', 18)print(m1.name)print(m1.age)print(m1.gender)print(m1.height)打印结果:
Kevin 18 不知道不知道- 我们给Maiyou类添加了一个函数:__getattr__
- 当代码中出现m1.gender和m1.height时,Python发现Maiyou类没有这两个属性,它就会调用__getattr__方法。
- 我们的方法逻辑是:把这个不存在的属性放在类字典中,并且默认值设置为”不知道“。
好像已经不用多解释了
- __getattr__是当属性不存在时,会被调用的一个魔术方法。
- 它默认会抛出AttributeError,但我们可以根据自己的需要重写它。
- __getattribute__是它的亲戚,但是用处不同。这个我们明天再聊。
相关帖子DA内容精选
|


雷达卡





京公网安备 11010802022788号







