zoukankan      html  css  js  c++  java
  • 【Python开发】Python中的class继承

    继承是面向对象的重要特征之一,继承是两个类或者多个类之间的父子关系,子进程继承了父进程的所有公有实例变量和方法。继承实现了代码的重用。重用已经存在的数据和行为,减少代码的重新编写,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也没有提供对接口的支持。接口是特殊的抽象类,接口没有数据成员,而是一组未实现的方法的集合。
  • 相关阅读:
    METHODS OF AND APPARATUS FOR USING TEXTURES IN GRAPHICS PROCESSING SYSTEMS
    Display controller
    Graphics processing architecture employing a unified shader
    Graphics-Processing Architecture Based on Approximate Rendering
    Architectures for concurrent graphics processing operations
    Procedural graphics architectures and techniques
    DYNAMIC CONTEXT SWITCHING BETWEEN ARCHITECTURALLY DISTINCT GRAPHICS PROCESSORS
    Thermal zone monitoring in an electronic device
    System and method for dynamically adjusting to CPU performance changes
    Framework for Graphics Animation and Compositing Operations
  • 原文地址:https://www.cnblogs.com/huty/p/8518000.html
Copyright © 2011-2022 走看看