[英]Python weird behaviour List of inherited classes
我正在建立一個語音識別系統,為此我建立了一個命令界面。 它們由主語,動詞,形容詞和通配符組成。 我是這樣實現的:
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
在類定義中寫words = []
,...使words
成為類綁定變量。 現在使用self.words
返回為類綁定變量定義的(最初為空)字典,該字典在派生類之間共享。
更好:刪除定義,並在派生類的__init__
添加self.words = []
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.