全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 数据分析师(CDA)专版
432 0
2022-04-24

作者:麦叔

来源:麦叔编程

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内容精选
  • 大厂数据分析面试指南!来自亚马逊、谷歌、微软、头条、美团的面试问题!
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群