我剛剛開始學習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