python之旅(六) - 自省
先看代码:
>>> class myClass:
def hello_1(self):
return 'hello_1'
def hello_2(self):
return 'hello_2'
>>> def main(index):
hello = getattr(myClass(),'hello_%s'%index,myClass().hello_1)
restr = hello()
print restr
>>> main(1)
hello_1
>>> main(2)
hello_2
>>> main(3)
hello_1
>>>
def hello_1(self):
return 'hello_1'
def hello_2(self):
return 'hello_2'
>>> def main(index):
hello = getattr(myClass(),'hello_%s'%index,myClass().hello_1)
restr = hello()
print restr
>>> main(1)
hello_1
>>> main(2)
hello_2
>>> main(3)
hello_1
>>>
重要的是getattr函数,它接受三个参数,第一个为模块,第二个为字符串,第三个参数为模板的属性或方法
getattr函数是这样工作的,在模块中查找是否有包括第二个参数的属性或方法,如果有,则返回找到的这个属性或方法名,如果没有则返回第三个参数的属性或方法,第三个参数是以默认值的方式存在的。

浙公网安备 33010602011771号