当子类在python中使用super关键字时,如何初始化父类

时间:2018-01-15 09:54:00

标签: python initialization parent-child multiple-inheritance super

我尝试运行这几行涉及super&的Python代码。 MRO。

class Child(Add, Sub, Mul, Sqroot, Div):正在决定输出的第一行,即当前Inside add class

请帮助我理解这个概念,因为如果我将该行更改为class Child(Sqroot, Add, Sub, Mul, Div):,则输出的第一行更改为Inside sqroot class

class Sqroot(object):
    def __init__(self):
        print 'Inside sqroot class'

    def sqroot(self, num):
        print 'The square root of the number is ',num**0.5

class Add(object):
   def __init__(self):
        print 'Inside add class'

   def add(self, num1, num2):
        print 'The sum is :', num1+num2

class Sub(object):
     def __init__(self):
        print 'Inside subtraction class'

def sub(self, num1, num2):
    print 'The subtraction is :', num1-num2


class Mul(object):
    def __init__(self):
        print 'Inside multiplication class'

    def mul(self, num1, num2):
        print 'The multiplication is :', num1*num2


class Div(object):
    def __init__(self):
        print 'Inside division class'

    def div(self, num1, num2):
        print 'The division is :', num1/num2


 class Child(Add, Sub, Mul,Sqroot, Div):
    def __init__(self):
        super(Child, self).__init__()


ob = Child()
ob.sqroot(9)
ob.add(6,4)
ob.sub(3,5)
ob.mul(6,4)
ob.div(6,4)

输出: -

Inside add class
The square root of the number is  3.0
The sum is : 10
The subtraction is : -2
The multiplication is : 24
The division is : 1

1 个答案:

答案 0 :(得分:1)

所有课程都应该调用他们的super(),e。 G:

class Sqroot(object):
    def __init__(self):
        print 'Inside sqroot class'
        super(Sqroot, self).__init__()

    def sqroot(self, num):
        print 'The square root of the number is ',num**0.5

为所有基类添加此项以启用对所有构造函数的正确调用(__init__() s)。

Python的内部逻辑会关注调用是否正确链接,i。即孩子会打电话给Add,Add会打电话给Sub,Sub会打电话给Mul等,直到Div打电话给对象(什么都不做)。

以下是类似链的图表:

enter image description here

你的看起来会更像这样:

             Add <--.
              ↓      \
             Sub      \
              ↓        \
object <-.   Mul        Child
          \   ↓
           \ Sqroot
            \ ↓
             Div