【发布时间】:2015-07-31 18:13:28
【问题描述】:
我有一个类的实例,我试图在其中使用父级中定义的方法。
我的代码产生以下错误:
if WordTrigger.isWordIn(story.getTitle()): return True:
TypeError: 未绑定的方法 isWordIn() 必须以 WordTrigger 实例作为第一个参数调用(取而代之的是 str 实例)
谁能引导我朝着正确的方向前进。即我应该使用 super() 2.7 版本吗?如果有怎么办?
class NewsStory(object):
"""
Data structure for RSS data feed collector
"""
def setUp(self):
pass
def __init__(self, cguid, ctitle, csubject, csummary, clink):
# A globally unique identifier for this news story.
self.cguid = cguid
# The news story's headline.
self.ctitle = ctitle
# A subject tag for this story (e.g. 'Top Stories', or 'Sports').
self.csubject = csubject
# A paragraph or so summarizing the news story.
self.csummary = csummary
# A link to a web-site with the entire story.
self.clink = clink
def getGuid(self):
return self.cguid
def getTitle(self):
return self.ctitle
def getSubject(self):
return self.csubject
def getSummary(self):
return self.csummary
def getLink(self):
return self.clink
#Trigger
class Trigger(object):
def evaluate(self, story):
"""
Returns True if an alert should be generated
for the given news item, or False otherwise.
"""
raise NotImplementedError
#WordTrigger
class WordTrigger(Trigger):
def __init__(self, cword):
# A globally unique identifier for this news story.
self.cword = cword
def isWordIn(self, ctext):
# Checks if word is in text and returns true if present
#Normalize case for word
self.cword = self.cword.lower()
# normalise text case and remove punctuation
self.ctext = self.ctext.lower()
exclude = set(str.punctuation)
self.ctext = ''.join(ch for ch in self.ctext if ch not in exclude)
# Check if word occurs in text
if self.cword in self.ctext:
return True
else:
return False
#TitleTrigger
class TitleTrigger(WordTrigger):
def evaluate(self, story):
"""
Returns True if an alert should be generated
for the given news item, or False otherwise.
"""
if WordTrigger.isWordIn(story.getTitle()): return True
else: return False
【问题讨论】:
-
我也应该包含这段代码:
-
类 NewsStory(object): def __init__(self, cguid, ctitle, csubject, csummary, clink): self.cguid = cguid self.ctitle = ctitle self.csubject = csubject self.csummary = csummary self.clink = clink def getTitle(self): return self.ctitle
-
谢谢,刚刚编辑,更容易阅读。
-
嗯,我认得这个……你目前正在参加 MITx/edX 课程吗?
-
是的,我参加了 MIT/edX 课程
标签: python python-2.7