__getattr__方法的运行机制

__getattr__方法是python的内置方法之一, 通常在不能够找到对象属性的时候被调用。
NB(注意): # 后面的部分表示输出结果

class Student:
    def __init__(self, name):
        self.name = name
    def __getattr__(self, name):
        return 'Student does not have `{}` attribute.'.format(str(name))


main = Student("褚璇玑")
print(main.name)	# 褚璇玑
print(main.age)		# Student does not have `age` attribute.

机制:__init__方法的运行机制这里不做过多讨论,当我们创建完成Student类的对象main后,我们打印实例化对象属性name的值,因为初始化过程时已经对name属性进行了赋值操作,因此我们得到输出结果“褚璇玑”,但是当我们打印age属性值时,因为Student类本身没有设置age属性对象,此时程序自动调用__getattr__(self, name)函数,因此打印出“Student does not have 'age' attribute”
此外需要注意__getattr__(self, name)中的参数name并不等同于__init__(self, name)中的参数name,事实上__getattr__(self, name)中的参数name可以替换为其它参数表示,比如attributeName, 从而避免混淆。
代码如下:

class Student:
    def __init__(self, name):
        self.name = name
    def __getattr__(self, attributeName):
        return 'Student does not have `{}` attribute.'.format(str(attributeName))


main = Student("褚璇玑")
print(main.name)	# 褚璇玑
print(main.age)		# Student does not have `age` attribute.
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勤奋的大熊猫

你的鼓励将是我写作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值