[英]How can I combine multiple function's output(strings) in Python?
我想有条件地合并多个函数返回的字符串; 某种程度上它不起作用:
file1.py
CALL_FUNCTION = {
‘function1’: function1
}
def function1():
return “hello”
def function2():
return “world”
file2.py
from file1 import CALL_FUNCTION
def final_function(condition):
final_string=CALL_FUNCTION[‘function1’] #Calls function1 from file1.py
if(condition)
from file1 import function2
final_string += function2()
return final_string
final_function(true) #This does not work; no error. Expected output is “hello world” when condition is true
您的代码有很多小错误。 我怀疑它们都是因为您通过手动重新键入代码而复制了代码,请在将来出现问题时使用复制粘贴功能。
这是您的代码的更正版本:
file1.py
def function1():
return "hello"
def function2():
return "world"
CALL_FUNCTION = {
'function1': function1
}
file2.py
from file1 import CALL_FUNCTION
def final_function(condition):
final_string=CALL_FUNCTION['function1']() #Calls function1 from file1.py
if condition:
from file1 import function2
final_string += function2()
return final_string
final_function(True) #This does not work; no error. Expected output is “hello world” when condition is true
但是之后,一切正常。 如预期那样调用函数,该函数按预期返回“ helloworld”,并且按预期不打印任何内容。
final_function(True)
仅在交互模式下打印某些内容,在批处理模式下,您需要添加print()才能实际看到结果。
print(final_function(True))
输出:
你好,世界
如果要根据“条件”返回不同函数的输出,则可以导入两个函数并在if-else子句中运行每个函数。 例如:
在file1.py中
def func1():
return "hello"
在file2.py中
def func2():
return "world"
然后在单独的file3.py中
from file1 import func1
from file2 import func2
def func3(cond):
out = func1()
if cond:
out+=' '+func2()
return out
if __name__ =='__main__':
print(func3(True))
输出:
hello world
令您惊讶的是,您在运行此代码时没有错误,因为您的代码中存在几个错误,因此我怀疑这与您所运行的代码不完全相同。 首先,请务必确定CALL_FUNCTION
以下function1
。 其次,存在一些语法错误-使用True
而不是true
以及适当的字符串引号( '
或"
)。
但是我相信这里的主要问题是,您实际上从未真正调用过 function1
,而是试图将函数对象final_string
到字符串,这是调用function2
的结果。 为了解决该问题,您需要更换:
final_string=CALL_FUNCTION['function1']
同
final_string=CALL_FUNCTION['function1']()
这样可以确保您调用function1
并将其结果保存到final_string
而不是保存function对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.