class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func_name = 'function' + self.i
self.func_name() # <-- this does NOT work.
def function1(self):
//do something
def function2(self):
//do something
Run Code Online (Sandbox Code Playgroud)
我得到的错误:TypeError:'str'对象不可调用
有人可以帮忙解决这个问题.我尝试了很多排列和组合,但无济于事!(注意:'self.func_name'也不起作用)
Jor*_*ley 39
def get(self):
def func_not_found(): # just in case we dont have the function
print 'No Function '+self.i+' Found!'
func_name = 'function' + self.i
func = getattr(self,func_name,func_not_found)
func() # <-- this should work!
Run Code Online (Sandbox Code Playgroud)
两件事情:
在第 8 行使用中,
func_name = '函数' + str(self.i)
将字符串到函数映射定义为,
self.func_options = {'function1': self.function1,
'function2': self.function2
}
Run Code Online (Sandbox Code Playgroud)所以它应该看起来像:
我的班级:
def __init__(self, i):
self.i = i
self.func_options = {'function1': self.function1,
'function2': self.function2
}
def get(self):
func_name = 'function' + str(self.i)
func = self.func_options[func_name]
func() # <-- this does NOT work.
def function1(self):
//do something
def function2(self):
//do something
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
27931 次 |
最近记录: |