python 对于子类构造函数重写父类构造函数的了解

1、对子类实例化的时候,子类的构造函数会覆盖父类的构造函数。super()相当于父类,所以在子类的构造函数中执行super(),就相当于执行了父类的构造函数
class Parent:
    def __init__(self):
        print('不想被覆盖')
    def add(self):
        print('add')

class Son(Parent):
    def __init__(self,a,b,c=10):
        super().__init__()
        print(a+b+c)
    def add2(self):
        print('add2')

son = Son(14,52)
son.add2()
son.add()
----------------------------
不想被覆盖
76
add2
add
----------------------------
2、对子类实例化的时候,如果子类没有显式的写构造函数,那么系统会自动给你添加构造函数并用super() 处理好。这个时候如果传了参数,那么父类的构造函数就要接收传入的参数,如下面的例子一样。
class Parent:
    def __init__(self,a,b):
        print(a,b)
    def add(self):
        print('add')

class Son(Parent):
    def add2(self):
        print('add2')

son = Son(14,52)
son.add2()
son.add()
----------------------------
14   52
add2
add
----------------------------
原文地址:https://www.cnblogs.com/huaniaoyuchong/p/13919917.html