命令行Python出现无法解释的名称错误



我正在学习优秀的"Python the Hard way",并将以下代码复制到一个名为mystuff.py的文件中:

class MyStuff(object):
    def __init__(self):
        self.tangerine = "And now a thousand years between"
    def apple(self):
        print "I AM CLASSY APPLES!"

终端内:

import mystuff
thing = MyStuff()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'MyStuff' is not defined

这种情况在今天的其他简单类中反复发生。有人能告诉我我做错了什么吗?

您可能想要thing = mystuff.MyStuff()(假设mystuff是类MyStuff所在的文件名)。

这里的问题是python如何处理命名空间。您可以通过导入将某些内容带入当前名称空间,但在如何将名称空间从一个文件合并到另一个文件方面有很大的灵活性。例如,

import mystuff

将从mystuff(模块/文件级)命名空间到当前命名空间的所有内容都带到当前命名空间中,但要访问它,您需要mystuff.function_or_class_or_data。如果你不想一直键入mystuff,你可以在当前模块(文件)中更改引用它的名称:

import mystuff as ms

现在,您可以通过:访问MyStuff

thing = ms.MyStuff()

(几乎)最后,是from mystuff import MyStuff。在这种形式中,您将MyStuff直接带到您的命名空间中,但mystuff中没有其他内容进入您的命名空间。

最后,(不推荐使用这个)from mystuff import *。这与上一个操作相同,但它也会获取mystuff文件中的所有其他内容并将其导入。

您将模块导入到本地命名空间,而不是导入类。如果你想在当前导入中使用该类,你需要:

thing = mystuff.MyStuff()

如果你想使用你的声明,你需要:

from mystuff import MyStuff

好吧,我想你得到了你需要的。但是怎么回事

import mystuff 
#with this type of import all the names in the `mystuff` module's namespace are not copied into current modules namespace.

所以你需要使用mystuff.MyStuff()

使用from mystuff import *mystuff模块的命名空间中的名称复制到当前模块的命名空间。现在您可以直接使用thing=MyStuff()