正如标题所说,我需要在导入到主文件的模块中重新导入模块吗?在这上面找不到任何东西,也不确定要搜索什么。因为这是不起作用的,直到我在epicness中导入了其他史诗
file1:
import epicness
import otherepic
epicness.someother(3)
美食主义:
def someother(x):
return dosomething(x)
另一部史诗:
def dosomething(x):
return x*4
发布于 2012-10-28 13:10:15
是的,您必须在每个模块中导入所需的所有内容。如果在module_a
中使用在module_b
中定义的函数B
,则必须在module_a
中导入module_b
,或者至少从B
导入module_b
函数。
解释:
在Python中,模块就是对象!导入模块时,将执行其代码,并将在其中定义的所有内容附加到模块对象的__dict__
$ echo 'a=1' > testing.py
$ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import testing
>>> 'a' in testing.__dict__
True
该模块的__dict__
还包含常用的全局内置组件。在模块中定义的任何内容都使用模块的__dict__
作为全局作用域。在python中,没有所谓的“全局变量”,即每个模块/类/函数都可以访问的变量。全局变量实际上只是模块的即时变量。
如果要将模块中的某些项导入到另一个模块的名称空间中,可以使用from
语法:
from module_a import functionA, functionB, classA, CONSTANT
您可以使用*
导入所有内容
from module_a import *
但是要避免使用from ... import *
语法!你会得到命名空间冲突,就像C中的includes。只有当模块在其文档中声明它是*
__-import安全时,才能这样做。要使模块导入__-*
安全,您可以定义__all__
全局变量,它应该是一个字符串序列,表示在执行*
-import时应该导出的标识符。
例如:
#module_a
A = 1
B = 2
__all__ = ['A']
#module_b
from module_a import *
print(A) #okay
print(B) #NameError, B was not exported!
https://stackoverflow.com/questions/13108758
复制相似问题