我正在构建一个语音识别系统,并为此构建了一个命令界面。它们由主语、动词、形容词和通配符组成。我是这样实现的:
class IWord(object):
strings = []
def recognize(self, word):
return word in self.strings
def add_synonym(self, word):
self.strings.append(word)
class Verb(IWord):
def __init__(self, words):
for word in words:
self.add_synonym(word)
class Adjective(IWord):
def __init__(self, words):
for word in words:
self.add_synonym(word)
class Object(IWord):
def __init__(self, words):
for word in words:
self.add_synonym(word)
class WildCard(IWord):
def recognize(self, word):
return word is not None & word
class ICommand(object):
words = []
parameters = []
但是我有两个继承自 ICommand 的类:
class Command1(ICommand):
def __init__(self):
self.words.append(Verb(['do']))
self.words.append(Object(['some']))
self.words.append(WildCard())
class Command1(ICommand):
def __init__(self):
self.words.append(Verb(['lorem']))
当我调试这部分时:
for command in self.Commands:
if command.recognize(text):
return command
似乎 command.words 包含“do”、“some”、通配符和“lorem”。我不明白那里出了什么问题。
请您参考如下方法:
self.words 是ICommand 类的words 属性(继承时不复制)。因此,当您追加到它时,它将追加到 ICommand 上,这将影响从它继承的每个类。
不过,也许更好的做法是:
class Command(object):
def __init__(self, words):
self.words = words
