Python - 使用继承方法的麻烦

时间:2015-07-31 18:13:28

标签: python python-2.7

我有一个类的实例,我正在尝试使用父类中定义的方法。

我的代码产生以下错误:

if WordTrigger.isWordIn(story.getTitle()): return True:
  

TypeError:必须使用WordTrigger实例作为第一个参数调用未绑定方法isWordIn()(改为使用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 

1 个答案:

答案 0 :(得分:0)

在您的班级TitleTrigger中,使用self。您可以通过类的实例访问该方法,而不是通过类对象本身访问该方法。

def evaluate(self, story):
    """
    Returns True if an alert should be generated
    for the given news item, or False otherwise.
    """    
    if self.isWordIn(story.getTitle()): return True
    else: return False