Python奇怪的行为继承类的列表

时间:2017-12-06 16:23:59

标签: 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):
    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'。我不知道那里出了什么问题。

2 个答案:

答案 0 :(得分:5)

self.wordswords类的ICommand属性(继承时不会复制)。因此,当您追加到它时,它将附加到ICommand,这将影响从其继承的每个类。

但是,可能更好的做法是:

class Command(object):
  def __init__(self, words):
    self.words = words

答案 1 :(得分:4)

在类定义中编写words = [],...使words成为一个类绑定变量。使用self.words现在返回为派生类在共享的类绑定变量定义的(最初为空)字典。

更好:删除定义并在派生类的self.words = []中添加__init__