簡體   English   中英

如何在Python中組合多個函數的輸出(字符串)?

[英]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對象。

PS:我建議翻閱PEP 8樣式指南 ,以使您的代碼更簡潔 ,將來更易於他人閱讀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM