学习python中的继承

发布时间:2020-02-28编辑:脚本学堂
python在类名后用一对圆括号表示继承关系, 括号中的类表示父类,如果父类定义了__init__方法,则子类必须显示地调用父类的__init__方法,如果子类需要扩展父类的行为,可以

python在类名后用一对圆括号表示继承关系, 括号中的类表示父类,如果父类定义了__init__方法,则子类必须显示地调用父类的__init__方法,如果子类需要扩展父类的行为,可以添加__init__方法的参数。

举例来演示继承的实现。
 

复制代码 代码如下:
class Fruit:
      def __init__(self, color):
           self.color = color
           print "fruit's color: %s" %self.color
 
      def grow(self):
           print "grow..."
 
class Apple(Fruit):                               #继承了父类
      def __init__(self, color):                  #显示调用父类的__init__方法
           Fruit.__init__(self, color)
           print "apple's color: %s" % self.color
 
class Banana(Fruit):                              #继承了父类
      def __init__(self, color):                  #显示调用父类的__init__方法
           Fruit.__init__(self, color)
           print "banana's color:%s" %s self.color
 
      def grow(self):                             #覆盖了父类的grow方法
           print "banana grow..."
 
if __name__ == "__main__":
apple = Apple("red")
apple.grow()
banana = Banana("yellow")
banana.grow()
 

输出结果:
           fruit‘s color : red
           apple's color : red
 
           grow...
 
           fruit's color : yellow
           banana's color : yellow
           banana grow...
 
抽象类的模拟

抽象类是对一类事物特征和行为的抽象,抽象类由抽象方法组成,python2.5没有提供抽象类的语法,抽象类的特征是不能被实例化,但是可以通过python的NotImplementedError类来模拟抽象类,NotImplementedError类继承自python运行时错误类RuntimeError。当对抽象类进行实例化时,将抛出异常。
模拟抽象类的实现
 

复制代码 代码如下:
def abstract():                                 #定义了全局函数
     raise NotImplimentedError(“abstract”):
        
class Fruit:
     def __init__(self):
          if self.__class__ is Fruit:            #如果实例化的类是Fruit,则抛出异常
               abstract()
          print "Fruit..."
 
class Apple(Fruit):
     def __init__(self):
          Fruit.__init__(self)
          print "Apple..."
 
if __name__ == "__main__":
apple = Apple()                                   #输出: Fruit   Apple
 

同样python也没有提供对接口的支持。接口是特殊的抽象类,接口没有数据成员,而是一组未实现的方法的集合。