为什么导入类时会出现名称错误?

5 投票
4 回答
14942 浏览
提问于 2025-04-16 05:09

我刚开始学习Python,但已经遇到了一些错误。我创建了一个叫做 pythontest.py 的文件,里面有以下内容:

class Fridge:
    """This class implements a fridge where ingredients can be added and removed individually
       or in groups"""
    def __init__(self, items={}):
        """Optionally pass in an initial dictionary of items"""
        if type(items) != type({}):
            raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
        self.items = items
        return

我想在交互式终端中创建这个类的新实例,所以我在终端里运行了以下命令:

>> import pythontest
>> f = Fridge()

结果我收到了这个错误:

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

交互式控制台找不到我创建的类。不过,导入是成功的,没有出现错误。

4 个回答

2

试试这个

import pythontest
f=pythontest.Fridge()

当你使用 import pythontest 时,变量名 pythontest 会被添加到全局命名空间中,并且指向模块 pythontest。要访问 pythontest 命名空间中的对象,你需要在对象名前加上 pythontest,然后跟一个点。

import pythontest 是导入模块和访问模块内对象的推荐方式。

from pythontest import *

几乎总是应该避免使用这种方式。只有在设置包的 __init__ 中的变量,或者在交互式会话中工作时,我觉得可以接受。避免使用 from pythontest import * 的原因之一是,这样会让你很难知道变量是从哪里来的。这会让调试和维护代码变得更加困难。而且,它也不利于模拟和单元测试。使用 import pythontest 可以给 pythontest 自己的命名空间。正如 Python 的哲学所说,“命名空间真是个好主意——我们应该多用这些!”

9

似乎没有人提到你可以这样做:

from pythontest import Fridge

这样一来,你就可以直接在命名空间中调用 Fridge(),而不需要使用通配符来导入。

5

你需要做的是:

>>> import pythontest
>>> f = pythontest.Fridge()

额外提示:你的代码可以这样写会更好:

def __init__(self, items=None):
    """Optionally pass in an initial dictionary of items"""
    if items is None:
         items = {}
    if not isinstance(items, dict):
        raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
    self.items = items

撰写回答