Python模块可以使用另一个文件的导入吗?

3 投票
6 回答
512 浏览
提问于 2025-04-15 11:31

我有这样的情况:

 # a.py  
 import os
 class A:
   ...

 # b.py
 import a
 class B(A):
   ...

在B类(b.py)中,我想使用在a.py中导入的模块(这里是os模块)。在Python中可以实现这种功能吗?还是说我需要在两个文件中都导入这些模块?

编辑:我并不担心导入的时间问题,我的问题是这些导入的代码让文件看起来很乱。我每个控制器(请求处理器)里最后都变成这样:

 from django.utils import simplejson
 from google.appengine.ext import webapp
 from google.appengine.ext.webapp import template
 from google.appengine.ext import db

这正是我想避免的。

6 个回答

0

你应该单独导入它。不过,如果你真的需要转发一些功能,可以从一个函数返回一个模块。只需这样做:

import os
def x:
   return os

但这看起来像是插件的功能——用对象和继承来解决这个问题会更好一些。

1

只需再次导入这些模块。

在Python中导入模块是个很轻松的操作。第一次导入一个模块时,Python会加载这个模块并执行里面的代码。之后再导入同一个模块时,你只会得到一个指向已经导入的模块的引用。

如果你想验证一下,可以自己试试:

# module_a.py
class A(object):
    pass

print 'A imported'

# module_b.py
import module_a

class B(object):
    pass

print 'B imported'

# at the interactive prompt
>>> import module_a
A imported
>>> import module_a     # notice nothing prints out this time
>>> import module_b     # notice we get the print from B, but not from A
B imported
>>> 
13

是的,你可以通过 a.os 来使用另一个文件中的导入内容。

不过,比较推荐的做法是只导入你真正需要的模块,而不是把它们串在一起(这样可能会导致循环引用的问题)。

当你导入一个模块时,Python 会把代码编译成对象,并把这些对象放进一个名字和模块对象的字典里。这个字典在 sys.modules 里。

import sys
sys.modules

>>> pprint.pprint(sys.modules)
{'UserDict': <module 'UserDict' from 'C:\python26\lib\UserDict.pyc'>,
 '__builtin__': <module '__builtin__' (built-in)>,
 '__main__': <module '__main__' (built-in)>,
 '_abcoll': <module '_abcoll' from 'C:\python26\lib\_abcoll.pyc'>,
# the rest omitted for brevity

当你再次尝试导入这个模块时,Python 会先检查这个字典,看看它是否已经存在。如果存在,它会把已经编译好的模块对象返回给你。如果不存在,它就会编译代码,然后把它放进 sys.modules 里。

因为字典是用哈希表实现的,所以查找速度非常快,所花的时间几乎可以忽略不计,相比之下,创建循环引用的风险要大得多。

编辑:我并不担心导入的时间,我的问题是这些导入的代码让文件看起来很乱。

如果你只有大约 4 或 5 个这样的导入,那就不会太乱。记住,“明确比隐含要好”。不过如果这真的让你很困扰,可以这样做:

<importheaders.py>
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db


<mycontroller.py>
from importheaders import *

撰写回答