__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.

猜你喜欢

转载自blog.csdn.net/u011699626/article/details/107933835