如何从另一个文件调用函数?

时间:2021-02-14 16:00:07

Sorry basic question I'm sure but I can't seem to figure this out.

对不起基本问题我很确定,但我似乎无法解决这个问题。

Say I have this program , the file is called pythonFunction.py:

假设我有这个程序,该文件名为pythonFunction.py:

def function():
   return 'hello world'

if __name__=='__main__':
   print function()

How can I call it in another program? I tried:

我怎么能在另一个程序中调用它?我试过了:

import pythonFunction as pythonFunction
print pythonFunction.function

Instead of 'hello world', I get ...I have done this in the past by making the first file a class, but I was wondering how to import the function correctly? If it helps, in my real file, I am printing a dictionary

而不是'你好世界',我得到...我过去通过将第一个文件作为一个类来完成这个,但我想知道如何正确导入函数?如果它有帮助,在我的真实文件中,我正在打印字典

1 个解决方案

#1


36  

You need to print the result of calling the function, rather than the function itself:

您需要打印调用函数的结果,而不是函数本身:

print pythonFunction.function()

Additionally, rather than import pythonFunction as pythonFunction, you can omit the as clause:

另外,您可以省略as子句,而不是将pythonFunction作为pythonFunction导入:

import pythonFunction

If it's more convenient, you can also use from...import:

如果它更方便,你也可以使用from ... import:

from pythonFunction import function
print function() # no need for pythonFunction.

#1


36  

You need to print the result of calling the function, rather than the function itself:

您需要打印调用函数的结果,而不是函数本身:

print pythonFunction.function()

Additionally, rather than import pythonFunction as pythonFunction, you can omit the as clause:

另外,您可以省略as子句,而不是将pythonFunction作为pythonFunction导入:

import pythonFunction

If it's more convenient, you can also use from...import:

如果它更方便,你也可以使用from ... import:

from pythonFunction import function
print function() # no need for pythonFunction.