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

2024-05-13 20:51:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习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

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

>> import pythontest
>> f = Fridge()

我得到这个错误:

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

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


Tags: 文件inpyself终端内容dictionarytype
2条回答

似乎没人提到你能做到

from pythontest import Fridge

这样就可以直接在命名空间中调用Fridge(),而不必使用通配符导入

你需要做的是:

>>> 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

试试看

import pythontest
f=pythontest.Fridge()

当您import pythontest时,变量名pythontest将添加到全局命名空间中,并且是对模块pythontest的引用。要访问pythontest命名空间中的对象,必须在它们的名称前加上pythontest和句点。

import pythontest导入模块和访问模块内对象的首选方法。

from pythontest import *

应该(几乎)永远避免。我认为它是可以接受的唯一一次是在包的__init__中设置变量,以及在交互会话中工作时。应该避免使用from pythontest import *的原因之一是,这使得很难知道变量从何而来。这使得调试和维护代码更加困难。它也不能帮助模拟和单元测试。import pythontestpythontest自己的名称空间。正如Python的禅宗所言,“名称空间是一个非常棒的想法——让我们做更多的事情吧!”

相关问题 更多 >