python多继承(钻石继承)的问题和解决

在菱形多继承中,如果用父类.__init__()来调用父类的初始化方法,最上层会执行两次,所以遇到这种情况,python中用super.__init__()来解决这个问题。

class Grand_father(object):
    def __init__(self):
        print('爷爷')


class Father_left(Grand_father):
    def __init__(self):
        super(Father_left,self).__init__()
        # Grand_father.__init__(self)
        print('左边爸爸')


class Father_right(Grand_father):
    def __init__(self):
        super(Father_right, self).__init__()
        # Grand_father.__init__(self)
        print('右边爸爸')


class Me(Father_right,Father_left):
    def __init__(self):
        super(Me, self).__init__()
        # Father_left.__init__(self)
        # Father_right.__init__(self)
        print('我')

def main():
    me = Me()

if __name__ == '__main__':
    main()

如果需要调用左边爸爸,那就执行super(右边爸爸类).

你可能感兴趣的:(python学习)