我刚刚开始学习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
交互式控制台找不到我做的类。虽然导入工作成功。没有错误。
只是好奇进口,为什么项目= {}在参数列表一个坏主意? – 2010-10-07 19:41:53
@RevolXadda:因为函数参数只处理一次。如果你给它可变的东西,它会在函数调用之间发生变异(如果你改变了它)。观察'def foo(d = [])的输出:d.append('foo');当你连续多次调用它时打印d'。 – Daenyth 2010-10-07 19:52:24
@Daenyth:谢谢!我完全忘记了这一点。 – 2010-10-07 20:00:45