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

Cur*_*nir 1 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 = []
Run Code Online (Sandbox Code Playgroud)

但是我有两个继承自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']))
Run Code Online (Sandbox Code Playgroud)

当我调试这个部分时:

for command in self.Commands:
    if command.recognize(text):
        return command
Run Code Online (Sandbox Code Playgroud)

似乎command.words包含'do','some',wildcard和'lorem'.我不知道那里出了什么问题.

int*_*ser 5

self.words是类的words属性ICommand(继承时不会复制它).所以当你附加到它时,它会附加到它上面ICommand,这将影响从它继承的每个类.

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

class Command(object):
  def __init__(self, words):
    self.words = words
Run Code Online (Sandbox Code Playgroud)