函数说明
getattr(object, name, default=None)
object:类实例
name:str 属性名
default:str 如果没有查找到,用该值替代
用法
实现反射,主要参考django的源码
class Test():
def __init__(self):
self.methods = ['method1', 'method2', 'method3']
def method1(self):
print('Method1')
def method2(self):
print('Method2')
def method3(self):
print('Method3')
def test(self, target):
if target in self.methods:
func = getattr(self, target)
func()
else:
print("无效调用")
if __name__ == '__main__':
test = Test()
target = 'method3'
test.test(target)
标签:__,target,self,getattr,test,def,函数
From: https://www.cnblogs.com/beichengshiqiao/p/16921834.html