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 のみを含む新しいリストを出力する必要があります。

実行するたびに、次のメッセージが表示されました。

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

初心者のように聞こえたら申し訳ありませんが、私は 1 か月前に Python の勉強を始めたばかりで、まったくの初心者です。前もって感謝します。

4

2 に答える 2

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    
于 2013-01-13T23:47:23.467 に答える
1

timc による回答では、コードでエラーが発生する理由とその修正方法が説明されていますが、クラスの現在の設計はかなり貧弱です。wordlist クラスは、外部データを操作する 2 つのメソッドのみを保持します。一般に、このためのクラスを作成する必要はありません。モジュールのグローバル スコープで直接定義するだけで済みます。wordlist クラスのより良い設計は、次のようになります。

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
于 2013-01-14T00:30:32.183 に答える