【发布时间】:2014-01-06 14:28:35
【问题描述】:
类似问题:Understanding A Chain of Imports in Python
注意:我使用的是 Python 3.3 我已经在同一个目录中设置了以下两个文件来向我自己解释导入,但是我仍然不知道它在做什么。我理解函数和类定义是需要运行的语句。
无标题.py:
import string
class testing:
def func(self):
try:
print(string.ascii_lowercase)
except:
print('not imported')
class second:
x=1
print('print statement in untitled executed')
stuff.py:
from untitled import testing
try:
t=testing()
t.func()
except NameError:
print('testing not imported')
try:
print(string.ascii_uppercase)
except NameError:
print('string not imported')
try:
print(untitled.string.ascii_uppercase)
except NameError:
print('string not imported in untitled')
try:
s=second()
print(s.x)
except NameError:
print('second not imported')
这是我运行 stuff.py 得到的输出:
print statement in untitled executed
abcdefghijklmnopqrstuvwxyz
string not imported
string not imported in untitled
second not imported
尽管在 stuff.py 中导入仅指定了测试类,但 untitled.py 中的打印语句仍被执行。此外,string 模块在 stuff.py 中的关系是什么,因为它可以从测试类内部调用,但不能从外部调用。
有人可以向我解释一下这种行为吗,“从导入”语句到底是做什么的(它运行什么)?
【问题讨论】:
标签: python python-3.x import