python3中 TypeError str object is not callable 我是这样定义的:threadingThreadtarget=fun_name+_fun 应该怎么解决
这个错误通常是由于尝试调用一个字符串对象而不是可以调用的函数对象引起的。在你的代码中,将 target 参数设置为 fun_name+'_fun' 字符串,这可能导致出现此错误。
要解决这个问题,你可以尝试以下几个步骤:
-
确保
fun_name+'_fun'是一个可调用的函数对象。你可以使用callable函数来检查它是否可调用,例如:print(callable(fun_name+'_fun'))。 -
确保
fun_name+'_fun'是一个函数对象而不是字符串。你可以使用type函数来检查它的类型,例如:print(type(fun_name+'_fun'))。 -
如果
fun_name+'_fun'是一个字符串,你需要将其转换为一个可调用的函数对象。你可以使用eval函数来执行字符串表示的函数名,例如:target = eval(fun_name+'_fun')。
以下是一个示例代码,演示了如何解决这个问题:
import threading
def my_function():
print("Hello from my_function!")
fun_name = 'my_function'
# 检查 fun_name+'_fun' 是否是可调用的函数对象
if callable(fun_name+'_fun'):
# 创建线程对象并指定目标函数
t = threading.Thread(target=fun_name+'_fun')
# 启动线程
t.start()
else:
print(fun_name+'_fun' + " is not a callable function.")
这个示例首先检查 fun_name+'_fun' 是否是可调用的函数对象,如果是,则创建线程对象并启动线程。如果不是,它将打印一条错误消息。请根据你的需求进行适当的修改
原文地址: https://www.cveoy.top/t/topic/iHHd 著作权归作者所有。请勿转载和采集!