继承类的Python行为列表
我正在建立一个语音识别系统,为此我为命令建立了一个接口。它们由主语、动词、形容词和通配符组成。我是这样实施的:继承类的Python行为列表,python,inheritance,Python,Inheritance,我正在建立一个语音识别系统,为此我为命令建立了一个接口。它们由主语、动词、形容词和通配符组成。我是这样实施的: 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):
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
self.words
是ICommand
类的words
属性(继承时不会复制)。因此,当您附加到它时,它将在ICommand
上附加到它,这将影响从它继承的每个类
不过,也许更好的做法是:
class Command(object):
def __init__(self, words):
self.words = words
写
字=[]
,。。。在类定义中,将words
作为类绑定变量。现在使用self.words
返回为派生类之间共享的类绑定变量定义的(最初为空)字典
更好的方法是:删除定义并在派生类的
初始化中添加self.words=[]
。编写words=[]
,。。。在类定义中,将words
作为类绑定变量。现在使用self.words
返回为派生类之间共享的类绑定变量定义的(最初为空)字典
更好的方法是:删除定义并在派生类的\uuu init\uuu
中添加self.words=[]
。以及如何将其仅放入子类中?将words=[]
添加到子类中。但实际上,最好使用一个通用的Command
类,将commands作为实例,而不是类。如何将其仅放入子类中?将words=[]
添加到子类中。但实际上,最好使用一个通用的Command
类,将命令作为实例,而不是类。为什么类绑定变量的继承在python中实现得如此糟糕?@Curunir我不会这么说。例如,如果你想在Java中的ICommand
类中定义一个static List words=new ArrayList()
,它的行为也会是一样的。为什么类绑定变量的继承在python中实现得如此糟糕?@Curunir我不会这么说。例如,如果您想在Java中的ICommand
类中定义一个static List words=new ArrayList()
,它的行为方式也会相同。