Skip to main content
 首页 » 编程设计

python 3 : How to call function from another file and pass arguments to that function

2025年04月02日8kuangbin

我想从另一个文件调用函数并将参数从当前文件传递到该文件。在下面的示例中,在文件 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')