gpt4 book ai didi

python - 如何使用方法名分配给变量来动态调用类中的方法

转载 作者:IT老高 更新时间:2023-10-28 22:15:18 32 4
gpt4 key购买 nike

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):
pass # do something

def function2(self):
pass # do something

这给出了错误:TypeError: 'str' object is not callable

我该怎么做呢?

注意:self.func_name 也不起作用

最佳答案

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!

关于python - 如何使用方法名分配给变量来动态调用类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16642145/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com