2013-01-13 23 views
2
class wordlist: 
    def is_within(word): 
     return 3 <= (len(word)) <= 5 
    def truncate_by_length(wordlist): 
     return filter(is_within, wordlist) 
    newWordlist = truncate_by_length(['mark', 'daniel', 'mateo', 'jison']) 
    print newWordList 

基本上它做什麼,給定一個詞的長度的最小值和最大值,(在給定的例子是3和5分別),它應該打印的新列表在距給定原始長度的那些長度內的單詞。例如上面給出的單詞mark,daniel,mateo和jison,它應該打印只包含mark,mateo和jison的新列表。Python編程:未定義全局名稱'is_within'。我使用的過濾器列表

每當我運行它,我收到以下內容:

Traceback (most recent call last): 
    File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 1, in <module> 
    class wordlist: 
    File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 6, in wordlist 
    newWordlist = truncate_by_length(['mark', 'daniel', 'mateo', 'jison']) 
    File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 5, in truncate_by_length 
    return filter(is_within, wordlist) 
NameError: global name 'is_within' is not defined 

對不起,如果我聽起來很小白等,但我剛開始學習Python的一個月前我就是一個完整的初學者用它。提前致謝。

回答

4

如果您在類方法定義中調用類方法,則需要調用'self'(例如,在您的示例中爲self.is_within)。你的類方法的第一個參數也應該是'self',它指向這個類的這個實例。檢查出Dive into Python是一個很好的解釋。

class wordlist: 
    def is_within(self, word): 
     return 3 <= (len(word)) <= 5 
    def truncate_by_length(self,wordlist): 
     return filter(self.is_within, wordlist) 

wl = wordlist()  
newWordList = wl.truncate_by_length(['mark', 'daniel', 'mateo', 'jison']) 
print newWordList  
+2

'self'是像任何其他一個普通變量;這只是約定,它是方法的第一個參數的名稱。他的方法沒有'self'參數,所以他會在'self'上得到一個'NameError'。 – icktoofay

+0

美好的一天!我只是做了你所說的,但仍然收到同樣的錯誤。我錯過了什麼嗎?就像icktoofay所說的那樣。 –

+0

@ictoofay謝謝你的澄清,你是完全正確的,我已經修改我的答案,因爲這樣 – timc

1

雖然timc的答案解釋了爲什麼你的代碼給出了一個錯誤以及如何解決它,但是你的類的當前設計相當差。您的wordlist類只包含兩種對外部數據進行操作的方法 - 通常不需要爲此創建類,您可以直接在模塊的全局範圍內定義它們。對於一個單詞表A類更好的設計是這樣的:

class wordlist(): 
    def __init__(self, wlist): 
     #save the word list as an instance variable 
     self._wlist = wlist 

    def truncate_by_length(self): 
     #truncante the word list using a list comprehension 
     self._wlist = [word for word in self._wlist if 3 <= len(word) <= 5] 

    def __str__(self): 
     #string representation of the class is the word list as a string 
     return str(self._wlist) 

使用方法如下:

w = wordlist(['mark', 'daniel', 'mateo', 'jison']) 
w.truncate_by_length() 
print w 
相關問題