官网解释:object.__getattr__(self, name)
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the(computed) attribute valueorraise anAttributeErrorexception.
当我们想调用Class中某些东西,而Class中没有,解释器铁定报错,停止运行,那有人就想了:真麻烦,每次都要重新执行一遍,如果当我调用错了内容,程序能把我这个错误当默认程序执行,而不停止我程序运行就好了。so,为了解决这类问题,就出来了__getattr__这个函数了。
我猜的,因为解决程序困难也是一种需求。
看没有__getattr的出错调用:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self):
self.name = 'Michael'
s = Student()
print s.name
print s.score #Class中没有这个属性
look, 第一个print正常执行,第二个由于Clas