python中的多继承和多态

来源:互联网 发布:数据库原理 编辑:程序博客网 时间:2024/05/25 12:21

多继承

就是一个子类继承多个父类:


多继承的例子,如下:

class Base(object):def test(self):print("------base")class A(Base):def test1(self):print("-----test1")class B(Base):def test2(self):print("----test2")class C(A,B):passc=C()c.test1()c.test2()c.test()

C也能继承Base

注:多继承中,每个父类都有相同的方法,子类继承时,会有一个继承顺序

想要查看该顺序的调用流程可以使用以下方法:

最后调用的是object方法,如果object方法也不存在,说明类中没有这个方法

print(子类类名.__mro__)
class Base(object):def test(self):print("-----Base")class A(Base):def test(self):print("----A")class B(Base):def test(self):print("----B")class C(A,B):def test(self):print("-----C")c=C()c.test()
多态

什么是多态:

定义时的类型和运行时的类型不一样,也就是定义时并不确定要调用的是哪个方法,只有运行的时候才能确定调用的是哪个

class Dog(object):def print_self(self):print("父类")class Xiaotq(Dog):def print_self(self):print("子类")def introduce(temp):temp.print_self()dog1=Dog()dog2=Xiaotq()introduce(dog1)introduce(dog2)
temp就是对象的引用,它和对象指向同一块空间

多态的作用:

在游戏中有多种类型的角色,要在玩家开始玩的时候才能选择,所以开始并不知道玩家选的什么角色,这就是多态



原创粉丝点击