[英]Python 3: How to call function from another file and pass arguments to that function ?
I want to call a function from another file and pass arguments from current file to that file.我想从另一个文件调用一个函数并将参数从当前文件传递到该文件。 With below example, In file bye.py I want to call function " me " from " hi.py " file and pass " goodbye " string to function " me ".在下面的例子中,在文件bye.py 中,我想从“ hi.py ”文件中调用函数“ me ”并将“ goodbye ”字符串传递给函数“ me ”。 How to do that ?怎么做 ? Thank you :)谢谢 :)
I have file hi.py我有文件 hi.py
def me(string):
print(string)
me('hello')
bye.py再见.py
from hi import me
me('goodbye')
What I got:我得到了什么:
hello
goodbye
What I would like:我想要什么:
goodbye
Generally when you create files to be imported you must use if __name__ == '__main__'
which evaluates to false in case you are importing the file from another file.通常,当您创建要导入的文件时,您必须使用if __name__ == '__main__'
如果您从另一个文件导入文件,它的计算结果为 false。 So your hi.py may look as:所以你的 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.