面向对象编程案例02--显示地调用父类的__init__()

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#面向对象编程案例02--显示地调用父类的__init__()



'''
继承是面向对象的重要特征之一,继承是2个类或多个类之间的父子关系,子类继承父类的所有共有实例变量和方法。
继承实现了代码的重用,减少代码的编写量
python在类名后用圆括号来表示继承关系,括号中的类表示父类
如果父类有init方法,则子类会显示地调用其父类的init方法,不需要重写定义。如果子类需要拓展父类的init方法,则可以父类的基础上继续拓展和添加新的属性和方法
'''



class Fruit():
    def __init__(self,color):
        self.color=color
        print '__init__()首先被调用,',self.color
    def grow(self):
        print 'grow():','xiaodeng'

        
class Apple(Fruit):
    def __init__(self,color):
        Fruit.__init__(self,color)#显示地调用父类的__init__()
        print "apple\'s color:",self.color
    
class Banana(Fruit):
    def __init__(self,color):
        Fruit.__init__(self,color)
        print 'banana\'s color:',self.color
    def grow(self):#覆盖父类的grow方法,对grow方法进行了重写
        print 'fengmei'


if __name__=="__main__":
    apple=Apple("red")
    print '---'*10
    apple.grow()
    print 
    print 
    banana=Banana("blue")
    banana.grow()

 

posted @ 2015-10-10 09:39  Xiao|Deng  阅读(322)  评论(1编辑  收藏  举报