2014-04-17 72 views
1

我有一個代碼如何從python的子類訪問超類的成員和變量?

class Trigger(object): 
    def evaluate(self,story): 
     Trigger.stroy=story 
     WordTrigger.isWordin(story) 
     raise NotImplementedError 

class WordTrigger(Trigger): 
    def __init__(self,word): 
     self.word=word 

    def isWordin(self, text): 
     rep = text.replace(string.punctuation, '') 
     toLower = rep.lower() 
     text = toLower.split(' ') 
     if(text in self.word): 
      return True 
     else: 
      return False 

class TitleTrigger(WordTrigger): 
    ... 

變量story是一類

class NewsStory: def __init__(self,guid, title, subject, summary, link): self.guid=guid self.title=title self.subject=subject self.summary=summary self.link=link def getGuid(self): return self.guid def getTitle(self): return self.title def getSubject(self): return self.subject def getSummary(self): return self.summary def getLink(self): return self.link

story=NewsStory(...) 如何訪問變量story其內置的高清功能的子類TitleTrigger

+0

最簡單的方法是用'Trigger.story'。如果你只是閱讀它(不分配新值),'self.story'也可以工作。如果您有任何不能使用的理由,請進一步解釋。 – BrenBarn

回答

0

我可以想到兩種方法。一個使用類變量,另一個使用初始化變量。這裏有一個例子是做兩件事:

class NewsStory: 
    def __init__(self,guid, title, subject, summary, link): 
     self.guid=guid 
     self.title=title 
     self.subject=subject 
     self.summary=summary 
     self.link=link 

    def getGuid(self): 
     return self.guid 

    def getTitle(self): 
     return self.title 

    def getSubject(self): 
     return self.subject 

    def getSummary(self): 
     return self.summary 

    def getLink(self): 
     return self.link 

class Trigger(object): 
    story = NewsStory("Guide","title", "subject", "summary","link") 

    def __init__(self): 
     self.mystory = NewsStory("Guide","title", "subject", "summary","link") 

    def evaluate(self,story): 
     Trigger.story=story 
     WordTrigger.isWordin(story) 
     raise NotImplementedError 

class WordTrigger(Trigger): 
    def __init__(self,word): 
     super(WordTrigger, self).__init__() 
     self.word=word 

    def isWordin(self, text): 
     rep = text.replace(string.punctuation, '') 
     toLower = rep.lower() 
     text = toLower.split(' ') 
     if(text in self.word): 
      return True 
     else: 
      return False 

class TitleTrigger(WordTrigger): 
    story = WordTrigger.story 

    def __init__(self, word): 
     super(TitleTrigger, self).__init__(word) 

if __name__ == "__main__": 
    print(TitleTrigger.story) 

    tt = TitleTrigger("hello") 
    print(tt.mystory) 

故事變量是一個類變量,而mystory變量是真實訪問,因爲你可以使用類似super(WordTrigger, self).__init__()初始化超類的實例變量,然後超變量可用。我希望幫助

編輯: 訪問並NewsStory更改標題,你可以這樣做:

print(tt.mystory.title) 
tt.mystory.title = "New title" 
print(tt.mystory.title) 
+0

'故事'不是字符串變量,而是其類型爲'NewsStory'的類 – Hash

+0

我的解決方案適用於任何類型。我已經用你的類更新過 – antimatter

+0

謝謝,以及如何訪問'getTitle'並將其值賦給來自函數TitleTrigger的另一個字符串變量。 – Hash