我有一个代码
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(...)
如何在子类class story
中访问变量TitleTrigger
及其内置的def函数?
答案 0 :(得分: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)