类的继承

什么时候用继承:有很多共同点时,用继承。较少共同点时,用组合

Python2有分新式类和经典类,Python3都是新式类

经典类:

def Old:
    pass

新式类:

def New():  #多了括号
    pass

派生:

继承的好处:

1.继承基类的方法,做出自己的改变或扩展(代码重用)

2.定义接口类,子类继承接口类,并且实现接口中定义的方法(接口继承:父类只定义一个方法名,子类去具体完善属于自己的方法)

 

 

一、单继承

1.1 子类可以使用父类的方法

class Father:    
    def __init__(self,name):
        self.name = name

    def father_run(self):
        print('%s is running '%self.name)

class Son(Father):
    pass

s = Son('son')  
s.father_run() #son is running 

 

1.2 子类定义与父类一样的属性名字,不会覆盖父类的属性,只是自己新增了一个属性

class Father:
    money = 10
    def __init__(self,name):
        self.name = name

    def father_run(self):
        print('%s is running '%self.name)

class Son(Father):
    money = 20
    pass
f = Father('father')
s = Son('son')
s.father_run() #son is running
print(f.money) #10
print(s.money) #20

 1.3 接口继承(父类接口只定义方法名,去限制它的子类必须要去重写这个方法)

import abc
class All_file(metaclass=abc.ABCMeta): 
    @abc.abstractmethod #限制子类必须要有这个方
    def read(self):
        pass

    @abc.abstractmethod #限制子类必须要有这个方法
    def write(self):
        pass

class Disk(All_file):
    def read(self):
        print('disk read')

    def write(self):
        print('disk write')

class Cdrom(All_file):
    def read(self):
        print('cdrom read')

    def write(self):
        print('cdrom write')

class Mem(All_file):
    def read(self):
        print('mem read')

    def write(self):
        print('mem write')

m1=Mem()
m1.read()
m1.write()

 

二、多继承(py2:深度优先 py3:广度优先)

 python3:经典类和新式类都是按广度优先继承的(原因是广度优先效率高于深度优先)

python2:经典类是按深度优先继承的,新式类是按广度优先继承的

 __mro__可查看线性继承关系

class A:
    pass
class B(A):
    pass
class C(A):
    pass
class D(B):
    pass
class E(C):
    pass
class F(D,E):
    pass

print(F.__mro__)
#(<class '__main__.F'>, <class '__main__.D'>, <class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

 

三、子类中使用super()调用父类方法

 

使用super()调用父类的构造方法__init__()

super().__init__(父类的构造函数形参)

class Vehicle1:
    Country='China'
    def __init__(self,name,speed,load,power):
        self.name=name
        self.speed=speed
        self.load=load
        self.power=power
    def run(self):
        print('开动啦')
        print('开动啦')
class Subway(Vehicle1):
        def __init__(self,name,speed,load,power,line):
           # super().__init__(name,speed,load,power)    
           super(Subway,self).__init__(name,speed,load,power)#super(__class__,self).__init__(name,speed,load,power)
           self.line=line
        def show_info(self):
            print(self.name,self.speed,self.load,self.power,self.line)
        def run(self):
            super().run()
            print('%s %s 线,开动啦' %(self.name,self.line))
line13=Subway('北京地铁','10km/s',1000000000,'',13)
line13.show_info()
line13.run()

 

posted on 2018-03-09 13:13  卓某  阅读(93)  评论(0编辑  收藏  举报

导航