2018-01-17 类的继承

继承是面向对象的重要特征之一;

继承关系:继承是相对两个类而言父子关系,子类继承了父类的所有共有属性和方法

继承实现了代码重用

例如:class Myclass (ParentClass)

如果弗雷定义了__init__方法,子类必须显示调用父类的__init__方法:

ParentClass.__init__(self,[args..])

如果子类需要扩展父类的行为,可以添加__init__方法的参数

第一种:常规继承父类,通过类名.__init__()

 People.__init__(self,'red')

class People(object):
    color='yellow'

    def think(self):
        print "i am a %s"% self.color
        print "i am a thinker"

class Chinese(People):
    pass
cn=Chinese()
print cn.color
cn.think()

class People(object):
    color='yellow'
    def __init__(self):
        print "__init..."
        self.dwell='earth'

    def think(self):
        print "i am a %s"% self.color
        print "i am a thinker"

class Chinese(People):
    pass
cn=Chinese()
print cn.dwell
cn.think()
class Chinese(People):
    def __init__(self):
        People.__init__(self,'red')
super  函数也可以继承父类,在子类中定义super 函数
super(Chinese,self).__init__('red')

class A(object):

def __init__(self):

print "enter a"

print "leave a"


class B(A):

def__init__(self):

print "enter B"

super(B,self).__init__()

print“leave B”

b=B()

class Chinese(People):
    def __init__(self):
        # People.__init__(self,'red')
        super(Chinese,self).__init__('red')


多重继承

Python 支持多重继承,即一个类可以继承多个父类:

语法:

class class_name (Parent_c1,parent_c2)

当父类中出现多个自定义的__init__方法时,多重继承只执行第一个类的__init__方法,其他不执行。

class People(object):
    color='yellow'
    def __init__(self,):
        self.dwell='earth'

    def think(self):
        print "i am a %s"% self.color
        print "my home is %s"% self.dwell


class Martian(object):
    color='red'
    def __init__(self):
        self.dwell='martian'
class Chinese(People,Martian):
    def __init__(self):
         People.__init__(self)
        # super(Chinese,self).__init__()
class People(object):
    color='yellow'
    def __init__(self,):
        self.dwell='earth'
        self.color='yellow'

    def think(self):
        print "i am a %s"% self.color
        print "my home is %s"% self.dwell


class Martian(object):
    color='red'
    def __init__(self):
        self.dwell='martian'

    def talk(self):
        print "i like talking"


class Chinese(Martian,People):
    def __init__(self):
        People.__init__(self)

cn=Chinese()
cn.think()
cn.talk()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值