Python中类的三种继承方式(隐式、显式、复合)

    技术2022-07-12  90

    1、隐式继承(implicit inheritance)

    class Parent: def implicit(self): print('Parent implicit()') class Child(Parent): pass#创建空的代码块 dad=Parent() son=Child() dad.implicit() son.implicit()

    输出: Parent implicit() Parent implicit() 2、显示覆写(explicit override)

    class Parent: def override(self): print('Parent override()') class Child(Parent): def override(self): print('Child override()') dad=Parent() son=Child() dad.override() son.override()

    输出: Parent override() Child override()

    也可以通过调用内置的super()函数调用父类方法来实现在程序运行前或者运行后覆写。

    class Parent: def altered(self): print('Parent altered()') class Child(Parent): def altered(self): print('-----------') super().altered()#调用父类中的altered()方法 print('-----------') dad=Parent() son=Child() dad.altered() son.altered()

    输出: Parent altered() ----------- Parent altered() ----------- 3、合成继承(composition inheritance)

    class Other: def implicit(self): print('Other implicit()') def override(self): print('Other override()') def altered(self): print('Other altered()') class Child: def __init__(self): self.other=Other() def implicit(self): self.other.implicit() def override(self): print('Child override()') def altered(self): print('*=============') self.other.altered() print('*=============') son=Child() son.implicit() son.override() son.altered()

    输出: Other implicit() Child override() *============= Other altered() *=============

    Processed: 0.012, SQL: 9