0

I tried running these few lines of Python code involving super & MRO.

The line class Child(Add, Sub, Mul, Sqroot, Div): is deciding the First line of the output i.e. currently Inside add class.

Please help me with the concept, because if I changed that line to class Child(Sqroot, Add, Sub, Mul, Div):, the first line of the output changed to 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)

OUTPUT:-

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

1 Answer 1

1

All your classes should call their 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

Add this for all your base classes to enable a proper calling of all constructors (__init__()s).

Python's internal logic will take care that the calls are chained properly, i. e. Child will call Add, Add will call Sub, Sub will call Mul, etc. until Div will call object (which does nothing).

Here's a diagram for a similar chain:

enter image description here

Yours would look more like this:

             Add <--.
              ↓      \
             Sub      \
              ↓        \
object <-.   Mul        Child
          \   ↓
           \ Sqroot
            \ ↓
             Div
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.