2010-10-07 78 views
4

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

交互式控制檯找不到我做的類。雖然導入工作成功。沒有錯誤。

回答

4

你需要做的:

>>> import pythontest 
>>> f = pythontest.Fridge() 

獎勵:你的代碼會這樣寫得更好:

def __init__(self, items=None): 
    """Optionally pass in an initial dictionary of items""" 
    if items is None: 
     items = {} 
    if not isinstance(items, dict): 
     raise TypeError("Fridge requires a dictionary but was given %s" % type(items)) 
    self.items = items 
+0

只是好奇進口,爲什麼項目= {}在參數列表一個壞主意? – 2010-10-07 19:41:53

+0

@RevolXadda:因爲函數參數只處理一次。如果你給它可變的東西,它會在函數調用之間發生變異(如果你改變了它)。觀察'def foo(d = [])的輸出:d.append('foo');當你連續多次調用它時打印d'。 – Daenyth 2010-10-07 19:52:24

+0

@Daenyth:謝謝!我完全忘記了這一點。 – 2010-10-07 20:00:45

2

嘗試

import pythontest 
f=pythontest.Fridge() 

當你import pythontest,變量名pythontest被加入到全局命名空間,並在模塊pythontest的參考。要訪問pythontest名稱空間中的對象,必須在前面加上pythontest後跟一個句點。

import pythontest在模塊中導入模塊和訪問對象的首選方法。

from pythontest import * 

應該(幾乎)總是要避免。我認爲可以接受的唯一情況是在包的內部設置變量__init__,以及在交互式會話中工作時。 from pythontest import *應該避免的原因之一是難以知道變量來自哪裏。這使得調試和維護代碼更困難。它也不協助嘲笑和單元測試。 import pythontest給出了pythontest它自己的命名空間。正如Python的禪說:「命名空間是一個好主意 - 讓我們做更多的!」

0

你應該導入的名字,即或是

import pythontest 
f= pythontest.Fridge() 

,或者

from pythontest import * 
f = Fridge() 
7

似乎沒有人提,你可以做

from pythontest import Fridge 

這樣,你現在可以在命名空間中直接調用Fridge()不使用通配符

相關問題