python 面向对象 super().__init__()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 14:01:36 2020

@author: lg
"""

class Init(object):
    
    
    def __init__(self, value):
        self.value=value
        print('start Init',self.value)
        



class Add2(Init):
    def __init__(self, value):

        print('start Add2',value)
        super(Add2, self).__init__(value)
        
#        print(self.value,'add','up')
        self.value = 2 + self.value
#        print(self.value,'add','down')



class Mul5(Init):
    def __init__(self, value):
        
        print('start Mul5',value)
        super(Mul5, self).__init__(value)
        
#        print(self.value,'mul5','up')
        self.value = self.value * 5
#        print(self.value,'mul5','down')



class Pro(Mul5, Add2):
    
    print('start Pro')
    pass


class Incr(Pro):
    print('start Incr1')
    def __init__(self, value):
        print('start Incr',value)
        
        
        super(Incr, self).__init__(value)
#        print(self.value,'Intr','up')
        self.value = self.value + 1
#        print(self.value,'Intr','down')

print(Incr.mro())
[, , , , , ]

说实话上面关于super的用法我并不十分理解,姑且说明一我的理解

  • 从Incr.mro()中我们可以看出类继承的关系,这里面有单继承和多继承
  • 这个例子的特别之处是value,比如在类Incr中并不是马上被执行 print(self.value,‘Intr’,‘up’)而是 super(Incr, self).init(value)被向上传递,一直传到根节点
p = Incr(5)
start Incr 5
start Mul5 5
start Add2 5
start Init 5
  • 也就是说根节点类Init中的value是5,然后在顺序执行
print(p.value) #查看你的结果如果是36 x

你可能感兴趣的:(python 面向对象 super().__init__())