【问题标题】:Python 3: How to call function from another file and pass arguments to that function ?Python 3:如何从另一个文件调用函数并将参数传递给该函数?
【发布时间】:2016-09-17 07:14:10
【问题描述】:

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

【问题讨论】:

标签: python function python-3.x


【解决方案1】:

通常,当您创建要导入的文件时,您必须使用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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-02
    • 2011-12-27
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 2019-07-25
    相关资源
    最近更新 更多