如何包含要在其他文件中使用的外部 Python 代码? [英] How to include external Python code to use in other files?

查看:59
本文介绍了如何包含要在其他文件中使用的外部 Python 代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在一个文件中有一组方法,有没有办法将这些文件包含在另一个文件中,但不带任何前缀(即文件前缀)调用它们?

If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?

如果我有:

[Math.py]
def Calculate ( num )

我该如何称呼它:

[Tool.py]
using Math.py

for i in range ( 5 ) :
    Calculate ( i )

推荐答案

您需要像这样将另一个文件作为模块导入:

You will need to import the other file as a module like this:

import Math

如果您不想在 Calculate 函数前面加上模块名称,请执行以下操作:

If you don't want to prefix your Calculate function with the module name then do this:

from Math import Calculate

如果要导入模块的所有成员,请执行以下操作:

If you want to import all members of a module then do this:

from Math import *

这是一个很好的章节 来自 Dive Into Python 对此进行了更深入的介绍主题.

Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

这篇关于如何包含要在其他文件中使用的外部 Python 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆