2017-12-06 11 views
1

나는 음성 인식 시스템을 건축하고있다, 나는 그것을위한 공용 영역을 건축한다. 그들은 주제, 동사, 형용사 및 와일드 카드로 구성됩니다. Python 괴괴 망측 한 행동 상속 한 종류의 명부

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'. 나는 거기에 무엇이 잘못되었는지 알지 못한다.

답변

4

words = [] 작성, ... 클래스 정의에 words 클래스 바인딩 변수를 만든다. self.words을 사용하면 파생 클래스간에 공유되는 클래스 바운드 변수에 대해 정의 된 (초기에 비어있는) 사전을 반환합니다.

더 나은 정의 : 정의를 제거하고 self.words = []을 파생 클래스의 __init__에 추가하십시오.

+0

왜 도대체 클래스 - 바운드 변수의 상속이 나쁘게 파이썬에서 구현 되었습니까? – Curunir

+1

@ 쿠르누르 나는 그렇게 말하지 않을 것이다. 예 : Java의'ICommand' 클래스에'static List words = new ArrayList ()'을 정의하면 같은 방식으로 동작합니다. –

5

self.wordsICommand 클래스의 words 속성입니다 (상속하면 복사되지 않음). 그래서 추가하면 ICommand에 추가되며 모든 클래스에 상속됩니다. 무언가 같이

은 아마,하지만 할 수있는 더 좋은 일이 될 것이다 :

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

그리고 어떻게 그 아이에게만 들어갈 수 있습니까? – Curunir

+1

'words = []'를 자식 클래스에 추가하십시오. 그러나 실제로는 클래스 대신 명령으로 인스턴스를 사용하는 일반적인'Command' 클래스를 갖는 것이 더 나을 것입니다. –