| __getattr__()方法 |
正常情况下,当我们调用类的方法或者属性时,如果搜索不到对应的方法或者属性,就会报错。
>>> class Student(object):
... def __init__(self):
... self.name = 'Micheal'
...
>>> s = Student()
>>> print s.name
Micheal
>>> print s.score
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
要避免这个错误,除了可以加上一个score属性外,python还有另外一个机制,那就是重写一个__getattr__()方法,动态返回一个属性。
class Student(object):
def __init__(self):
self.name = 'Michael'
def __getattr__(self, attr):
if attr=='score':
return 99
当调用不存在的属性的时候,比如score,python解释器就会调用__getattr__(self, 'score') 来尝试获得属性。
注意:这里自动把不存在的属性转换为了字符串的形式,然后传到函数__getattr__(self,attr)__ 中,并赋值给attr,所以这是的attr是一个字符串。
>>> s = Student()
>>> s.name
'Michael'
>>> s.score
99
返回函数也是完全可以的:
class Student(object):
def __getattr__(self, attr):
if attr=='age':
return lambda: 25
只是调用方式要变为,因为返回的是一个函数对象(类似函数指针)
>>> s.age()
25
注意,只有在没有找到属性的情况下,才调用__getattr__ ,已有的属性,比如name,不会在__getattr__ 中查找。
此外,注意到任意调用如s.abc都会返回None,这是因为我们定义的__getattr__ 默认返回就是None。要让class只响应特定的几个属性,我们就要按照约定,抛出AttributeError的错误:
class Student(object):
def __getattr__(self, attr):
if attr=='age':
return lambda: 25
raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)
这实际上可以把一个类的所有属性和方法调用全部动态化处理了,不需要任何特殊手段。
1118

被折叠的 条评论
为什么被折叠?



