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

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

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

最佳答案

似乎没有人提到你可以做到

from pythontest import Fridge

这样您现在可以直接在命名空间中调用 Frid​​ge() 而无需使用通配符导入

关于python - 为什么在导入类时出现名称错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3885084/

相关文章:

python - 安装你自己的 Python 包

python - 在 SQLAlchemy 列属性中使用 python 日期函数

Python:从http到csv

python - shell 文本到 python 字符串

javascript - 如何在 JavaScript 中定义本地文件的路径

python - 停止迭代 : generator_output = next(output_generator)

python - 如何在 Pandas 中执行 groupby 并计算原始数据集中每行的平均值

python - 快速和慢速分词器产生不同的结果

python - 如何在我的类中设置默认字段以迁移到 Django Rest 中的 sqlite 数据库?

python - 在调用者线程中捕获线程的异常?