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