首页 > 其他 > 详细

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

时间:2015-10-10 10:20:13      阅读:118      评论:0      收藏:0      [点我收藏+]
# -*- 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()

 

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

原文:http://www.cnblogs.com/dengyg200891/p/4865860.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!