簡體   English   中英

Python 3:如何從另一個文件調用函數並將參數傳遞給該函數?

[英]Python 3: How to call function from another file and pass arguments to that function ?

我想從另一個文件調用一個函數並將參數從當前文件傳遞到該文件。 在下面的例子中,在文件bye.py 中,我想從“ hi.py ”文件中調用函數“ me ”並將“ goodbye ”字符串傳遞給函數“ me ”。 怎么做 ? 謝謝 :)

我有文件 hi.py

def me(string):
    print(string)
me('hello')

再見.py

from hi import me
me('goodbye')

我得到了什么:

hello
goodbye

我想要什么:

goodbye

通常,當您創建要導入的文件時,您必須使用if __name__ == '__main__'如果您從另一個文件導入文件,它的計算結果為 false。 所以你的 hi.py 可能看起來像:

def me(string):
    print(string)

if __name__ == '__main__':
    # Do some local work which should not be reflected while importing this file to another module.
    me('hello')

暫無
暫無

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

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