Python导入模块在另一个文件中

Python导入模块在另一个文件中

本文介绍了Python导入模块在另一个文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将一个项目(以前是一个大文件)重构为几个单独的python文件,每个文件都运行应用程序的特定部分.例如,GUIthread.py运行GUI,Computethread.py做一些数学运算,等等.

I'm currently re-factoring a project (formerly big one file) into several seperate python files, each of which runs a specific part of my application.Eg, GUIthread.py runs the GUI, Computethread.py does some maths, etc etc.

每个线程都包括从导入的模块(如mathtimenumpy等)中使用的功能.

Each thread includes the use of functions from imported modules like math, time, numpy, etc etc.

我已经有一个文件globalClasses.py,其中包含我的数据类型等的类定义,每个.py文件都会在开始时按照以下建议进行导入: http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm .这运作良好.

I already have a file globalClasses.py containing class definitions for my datatypes etc, which each .py file imports at the start, as per recomendation here: http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm . This is working well.

我想做的是将所有3rdparty模块导入也都保存在globals文件中,这样我就可以编写例如import math一次,但是我所有的项目文件都可以使用函数.

What I would like to do is have all my 3rdparty module imports in the globals file as well, so that I can write, for example, import math once but have all of my project files able to use math functions.

问题:

1.这可能吗?

2.这是一个好主意/Python的良好做法吗?

我当前的解决方案只是放上

My current solution is just to put

import math
import time
import numpy
...

(以及我正在使用的所有其他模块的导入)

(plus imports for all the other modules I'm using as well)

位于我项目中每个文件的顶部...但这似乎不太整洁,并且在将代码块从一个文件移动到另一个文件时,很容易忘记移动依赖项的import语句...

at the top of every file in my project... But that doesn't seem very tidy, and it's easy to forget to move a dependency's import statement when moving code-chunks from file to file...

推荐答案

是的,我想有一种更优雅的方法可以节省多余的代码行.假设您要导入一些模块math, time, numpy(例如),然后可以创建文件importing_modules(例如)并将各种模块导入为from module_name import *,因此importing_modules.py可能看起来像这样:

Yeah I guess there is a more elegant way of doing this which will save redundant line of code. Suppose you want to import some modules math, time, numpy(say), then you can create a file importing_modules(say) and import the various modules as from module_name import *, So the importing_modules.py may look something like this:

importing_modules.py

from math import *
from numpy import *
from time import *

main.py

from importing_modules import *
#Now you can call the methods of that module directly
print sqrt(25) #Now we can call sqrt() directly in place of math.sqrt() or importing_modules.math.sqrt().

这篇关于Python导入模块在另一个文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:11