【发布时间】:2015-08-16 18:56:37
【问题描述】:
有我认为是一个不寻常的问题。我有一个 Python 脚本 script1.py 定义 class BaseClass(dict),还有另一个脚本定义 class ChildClass(BaseClass)。
ChildClass 使用from script1 import * 导入第一个脚本,但是当尝试运行ChildClass 时,我得到NameError: name 'BaseClass' is not defined。
# script1.py
...
class BaseClass(dict):
def __init__(self, params):
pass
...
# ChildClass.py
from script1 import *
class ChildClass(BaseClass):
...
完全相同的脚本在我的家用机器 (Ubuntu 15.04) 上运行良好,但我的工作机器 (Windows 7 Pro) 出现上述 NameError。
我在python环境中检查过,确实找到了script1.py文件,但实际上并没有导入里面的任何函数。
>>> from script1 import *
>>> BaseClass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'BaseClass' is not defined'
我在想问题是 Windows Python 和 Linux Python 之间的区别,但我以前从未遇到过这种问题。欢迎任何见解。
【问题讨论】:
-
您在
sys.path的某个文件夹中还有一些名为script1的其他脚本,它不包含BaseClass。试试import script1; print script1.__file__ -
执行
import script1,然后打印script1.__file__,看看它在哪里找到模块。 -
@kindall @Brenbarn 这样做会导致
AttributeError: 'module' object has no attribute '__file__。不过,我知道它正在读取 script1,因为尝试输入import randomstringao会引发 ImportError。 -
这个模块的实际名称是什么?因为你得到的错误通常表明一个内置模块。
-
您确定两台计算机都使用 Python 2 吗? Python 2 和 3 的相对导入规则有些不同,it looks like you're getting the built-in
parsermodule on one machine.
标签: python linux windows python-2.7 python-import