多继承、多态

1.多继承

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):
pass
#def test(self):
# print("-----C")


c = C()
c.test()

print(C.__mro__)

2.多态
class Dog(object):
def print_self(self):
print("大家好,我是xxxx,希望以后大家多多关照....")

class Xiaotq(Dog):
def print_self(self):
print("hello everybody, 我是你们的老大,我是xxxx")


def introduce(temp):
temp.print_self()


dog1 = Dog()
dog2 = Xiaotq()

introduce(dog1)
introduce(dog2)


继承可以把父类的所有功能都直接拿过来,这样就不必重零做起,子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写;

有了继承,才能有多态。在调用类实例方法的时候,尽量把变量视作父类类型,这样,所有子类类型都可以正常被接收;

旧的方式定义Python类允许不从object类继承,但这种编程方式已经严重不推荐使用。任何时候,如果没有合适的类可以继承,就继承自object类。

原文地址:https://www.cnblogs.com/loser1949/p/9195849.html