python导入其他文件,Python导入模块在另一个文件中

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.

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

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.

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.

Questions:

1. Is this possible?

2. Is it a good idea/is it good Python practice?

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)

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...

解决方案

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().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值