2013-12-23 122 views
1

我正在努力通過學習Python的難方式練習49(http://learnpythonthehardway.org/book/ex49.html),我需要比較兩個不同的對象。這是我需要的測試代碼:比較對象與鼻子

class ParserError(Exception): 
    pass 


class Sentence(object): 

def __init__(self, subject, verb, object): 
    # remember we take ('noun','princess') tuples and convert them 
    self.subject = subject[1] 
    self.verb = verb[1] 
    self.object = object[1] 


def peek(word_list): 
    if word_list: 
     word = word_list[0] 
     return word[0] 
    else: 
     return None 


def match(word_list, expecting): 
    if word_list: 
     word = word_list.pop(0) #Here it's returning 'noun' from the noun/princess tuple 

     if word[0] == expecting: #Here it's testing whether or not the new item in the  0 position ('noun' in this case) = expecting 
      return word 
     else: 
      return None 
    else: 
     return None 


def skip(word_list, word_type): 
    while peek(word_list) == word_type: 
     match(word_list, word_type) 


def parse_verb(word_list): 
    skip(word_list, 'stop') 

    if peek(word_list) == 'verb': 
     return match(word_list, 'verb') 
    else: 
     raise ParserError("Expected a verb next.") 


def parse_object(word_list): 
    skip(word_list, 'stop') 
    next = peek(word_list) 

    if next == 'noun': 
     return match(word_list, 'noun') 
    if next == 'direction': 
     return match(word_list, 'direction') 
    else: 
     raise ParserError("Expected a noun or direction next.") 


def parse_subject(word_list, subj): 
    verb = parse_verb(word_list) 
    obj = parse_object(word_list) 

    return Sentence(subj, verb, obj) 


def parse_sentence(word_list): 
    skip(word_list, 'stop') 

    start = peek(word_list) 

    if start == 'noun': 
     subj = match(word_list, 'noun') 
     return parse_subject(word_list, subj) 
    elif start == 'verb': 
     # assume the subject is the player then 
     return parse_subject(word_list, ('noun', 'player')) 
    else: 
     raise ParserError("Must start with subject, object, or verb not: %s" % start) 

我的問題是在那裏我應該創建一個句子對象功能parse_sentence。所以,我需要在我的測試代碼來創建另一個句子的對象,並確保它是相同的:

def test_parse_subject(): 
    word_list = [('verb', 'kill'), ('direction', 'north')] 

    subj = ('noun', 'princess') 
    verb = ('verb', 'kill') 
    obj = ('direction', 'north') 
    obj_sent = Sentence(subj, verb, obj) 

    assert_equal(parser.parse_subject(word_list, subj), obj_sent) 

但我不斷收到這個追蹤錯誤:

Traceback (most recent call last): 
    File "G:\Python27\lib\site-packages\nose\case.py", line 197, in runTest 
    self.test(*self.arg) 
    File "G:\Users\Charles\dropbox\programming\parsing_test\skeleton\tests\parser_tests.py", line 45, in test_parse_subjec 
t 
    assert_equal(parser.parse_subject(word_list, subj), obj_sent) 
AssertionError: <ex49.parser.Sentence object at 0x02651C50> != <ex49.parser.Sentence object at 0x02651C30> 

,所以它不是返回的對象一樣,但我很確定他們是。我給了他們正確的論點。如果對象相同,我如何確認?在此先感謝

回答