python面向对象的三大特征--继承

#什么时候用继承
#1.当类之间有显著不同,并且较小的类是较大的类所需的组件时,用组合比较好
#2.当类之间有很多相同的功能,提供这些共同的功能做成基类,用继承比较好


class Dad:

    "这个是爸爸类"
    money=10

    def __init__(self,name):
        print("爸爸")
        self.name=name

    def hit_son(self):
        print("%s 正在打儿子" %self.name)


class Son(Dad):
    money = 10000000
    #当子类中有跟父类属性同名的数据属性或者方法属性时会覆盖父类中的属性,当子类中没有时会优先调用父类方法
def __init__(self,name,age): self.name=name self.age=age def hit_son(self): print("来自儿子类",self.name) #print(Son.money) #Son.hit_son() # print(Dad.__dict__) # print(Son.__dict__) # s1=Son("TANG") # # print(s1.name) # print(s1.money) # s1.hit_son() #现在子类查找自己的init方法 s1=Son("alex","18") s1.hit_son() # print(Son.money) # print(Dad.money)




#使用abc模块实现子类必须实现基类的方法
import abc
#接口继承

class All_file(metaclass=abc.ABCMeta):
@abc.abstractmethod

def read(self):
pass

@abc.abstractmethod
def write(self):
pass


#接口:接口就是一个函数,接口继承:定义一个基类,基类当中把自己的方法定义成基类函数,来一个子类继承他就必须实现基类的方法
#使用abc模块实现子类必须实现基类的方法


class Disk(All_file):

def read(self):
print("disk read")

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


class Cdroom(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")

def sad(self):
print("jjj")


m1=MEm()
# m1.sad()
# m1.read()
# m1.write()




#继承顺序:1.python2:分经典类和新式类 经典类指不继承基类object的类,新式类继承基类object的类
2.python3:默认为新式类即默认继承object基类
3.经典类默认是深度有限的继成顺序,新式类默认是广度优先的继承顺序,新式类中可以使用类属性.__mro__查看类的继承顺序
class A:
def test(self):
print("A")

#当类是新式类是继承查找顺序为广度优先

class B(A):
def test(self):
print("B")


class C(A):
def test(self):
print("C")

class D(B):
def test(self):
print("D")


class E(C):
def test(self):
print("E")


class F(D,E):
pass
# def test(self):
# print("F")

f1=F()
f1.test()#F--->D---->B ---->E---->C---->A

print(F.__mro__)
#python到底是如何实现继承的,对于你定义的每一个类,python会计算出一个方法解析顺序(MRO)元祖,这个MRO
#列表就是一个简单的,所有基类的线性顺序元祖,python3默认继承object基类



 

猜你喜欢

转载自www.cnblogs.com/tangcode/p/11287046.html