Skip to content

[Python learning] Inheritance and Polymorphism

Gukie edited this page Dec 19, 2017 · 1 revision

outline:

  • Python是多继承的
  • 所有的类,默认继承自 object
  • 子类可以复写父类的方法
  • 子类如果复写了 **init()**方法,第一行需要需要是 super().init(), 否则子类调用父类的方法时会出错
  • 如果继承多个父类,并且这些父类有方法名相同的方法,那么子类自调用该方法的时候,是按继承的顺序来的,在最前面的父类的该方法会被调用

object的三个方法

  • new() : 创建对象的方法
  • init() : 初始化attribute的方法
  • str() : 类似于Java中的 toString()

class Cls1:
    def __init__(self):
        super().__init__()
        print("Cls1 init")

    def hello(self):
        print("Cls1")

class Cls2:
    def __init__(self):
        super().__init__()
        print("Cls2 init")
    def hello(self):
        print("Cls2")


class Cls3:
    def __init__(self):
        super().__init__()
        print("Cls3 init")

    def hello(self):
        print("Cls3")



# class Child(Cls1,Cls2,Cls3):
class Child(Cls2, Cls1, Cls3):
    def __init__(self):
        super().__init__()
        print("child init")
    def test(self):
        print("test")



child = Child()
child.hello();

Output:

Cls3 init
Cls1 init
Cls2 init
child init
Cls2          # 哪个父类在继承语句的第一个位置,就调用的是哪个父类的方法

Clone this wiki locally