我刚开始学习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
这样您现在可以直接在命名空间中调用 Fridge()
而无需使用通配符导入
关于python - 为什么在导入类时出现名称错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3885084/