gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:30:38 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com