我正在努力学习Python ex48。以下是我的代码:
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, obj):
self.subject = subject[1]
self.verb = verb[1]
self.object = obj[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)
if word[0] == 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_word = peek(word_list)
if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next")
def parse_subject(word_list):
skip(word_list, 'stop')
next_word = peek(word_list)
if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
raise ParserError("Expected a verb next.")
def parse_sentence(word_list):
subj = parse_subject(word_list)
verbj = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj)
我正在尝试在终端中运行此脚本。我运行python3并首先导入脚本然后尝试运行其中一个函数。但是,我收到以下错误:
我想知道如何才能正确地从班级中获取此功能。谢谢!
答案 0 :(得分:2)
如果你正在使用课程,你的功能会有所不同。函数定义中的第一个参数将引用对象本身,通常称为self
,就像在__init__
中一样。向每个其他实例方法添加self
参数,然后根据需要使用其他参数(如word_list
)。然后使用self.method_name
参考这些实例方法。
def parse_subject(self, word_list):
self.skip(word_list, 'stop')
next_word = self.peek(word_list)
if next_word == 'noun':
return self.match(word_list, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
raise ParserError("Expected a verb next.")
以上只是一个示例 - 您需要以类似的方式修改其他实例方法。