Python入门到精通三天速成第二讲——类与继承
子类扩展了超类(父类)的定义。要指定超类,可在 class 语句中的类名后加上超类名,并将其用圆括号括起。 class Filter: def init(self): self.blocked = [] def filter(self, sequence): return [x for x in sequence if x not in self.blocked] class SPAMFilter(Filter): # SPAMFilter是Filter的子类 def init(self): # 重写超类Filter的方法init self.blocked = ['SPAM'] Filter 是一个过滤序列的通用类。实际上,它不会过滤掉任何东西。 >>> f = Filter() >>> f.init() >>> f.filter([1, 2, 3]) [1, 2, 3] Filter 类的用途在于可用作其他类(如将 'SPAM' 从序列中过滤掉的 SPAMFilter 类)的基类(超类)。 >>> s = SPAMFilter() >>> s.init() >>> s.filter(['SPAM', 'SPAM', 'SPAM', 'SPAM', 'eggs', 'bacon', 'SPAM']) ['eggs', 'bacon'] 请注意 SPAMFilter