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

标签 python

抱歉,基本问题我确定,但我似乎无法弄清楚。

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

def function():
   return 'hello world'

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

如何在另一个程序中调用它? 我试过了:

import pythonFunction as pythonFunction
print pythonFunction.function

我得到的不是“hello world”,而是...我过去通过将第一个文件设为类来完成此操作,但我想知道如何正确导入该函数?如果有帮助,在我的真实文件中,我正在打印一本字典

最佳答案

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

print pythonFunction.function()

另外,您可以省略 as 子句,而不是 import pythonFunction as pythonFunction:

import pythonFunction

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

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

关于python - 如何从另一个文件调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7701646/

相关文章:

python - f-string: single '}' is not allowed Python SPARQL 查询问题

python - 在cloudcontrol上,如何进行URL重写?

python - JavaScript 的 String.fromCharCode 有 Python 版本吗?

python - 两个客户端无法在套接字客户端-服务器连接中相互通信

python - Pycharm jupyter单元格背景

python - 您不认为从系列列表创建 DataFrame 很奇怪吗?

python - 是否有纠正大小写的python拼写纠正库?

python - 在 Python 中运行大型函数时出现类型错误

python - Kevin Bacon 游戏的最短路径图遍历

python - 从子流程的子流程捕获输出