python super使用

class Base1():
    def __init__(self, name):
        self._name = name
        print("name", self._name)
    
    def my_func(self):
        print(self._name)
        

class Base2():
    def __init__(self, age):
        self._age = age
        print("age",self._age)
        
    
    def my_func(self):
        print(self._age)
        
        
class Son(Base1, Base2):
    
    def __init__(self, name, age):
        # 子类多继承时,super参数时子类时,制有第一个继承基类第一个类Base1被初始化
        super(Son, self).__init__(age)
        
        # 初始化Base2
        super(Son, self).__init__(name)
        

    def my_func(self):
        print("son")
        


c = Son("ls", 20)
c.my_func() 
# output:
# name 20
# name ls
# son


class Son1(Base1, Base2):
    
    def __init__(self, name, age):
        
        # super参数填写父类时,按继承顺序只能Base1可以被初始化
        # super(Base1, self).__init__(name) # ok
        # super(Base2, self).__init__(age) # error

        # 不是顺序初始化,报错
        # super(Base2, self).__init__(name) # error
        # super(Base1, self).__init__(age)  # not reach
        
        # 直接使用基类类名调用__init__(), 正确执行
        Base1.__init__(self, name) 
        Base2.__init__(self, age)
        
        
    def my_func(self):
        print("son")

c1 = Son1("ls", 20)
c1.my_func()
# output:
# name ls
# 20
# son



class Son2(Base1, Base2):
    
    def __init__(self, name, age):
        # 子类多继承时,super无参数时,只有第一个继承基类第一个类Base1被初始化
        super().__init__(name)
        super().__init__(age)
        
        # supper加子类名,效果同上
        # super(Son2,self).__init__(name)
        # super(Son2,self).__init__(age)
        
    def my_func(self):
        print("son")
        
c1 = Son2("ls", 20)
c1.my_func()
# output:
# name ls
# name 20
# son

总结:多继承,使用基类名称调用__init__进行初始化父类

你可能感兴趣的:(python,super)