-1

I have a class structure definition as follows: What I fail to understand is, how does Super() use the code from the Super class in the function of the base class here?

class Std(object):    
    def __init__(self):
        self.W = defaultdict(int)

    def update(self, vect, label):
        self.bias += label
        for k, v in vect.items():
            self.W[k] += v * label
class Avg(Std):
    def __init__(self):
        super(Avg, self).__init__()
        self.U = defaultdict(int)
        self.beta = 0

    def update(self, vect, label):
        super(Avg, self).update(vect, label)
        self.beta += label * self.count
        for k, v in vect.items():
            self.U[k] += v * label * self.count

Can someone explain to me how many lines code are actually there in the update method of the Avg class and how does the Super() work here?

Sumedha Nagpal
  • 163
  • 2
  • 15
  • `super()` gives you access to the existing methods of another class in the class MRO; meaning you are simply *calling another method*, just one can have the exact same name as one already present on the instance. – Martijn Pieters Oct 28 '16 at 17:40
  • super *calls* the method from the base class. As for how many lines of code, you can count them. – Daniel Roseman Oct 28 '16 at 17:40
  • @DanielRoseman saying "base class" is misleading. It does not always call a base class, it can call a sibling class. – wim Oct 28 '16 at 17:44
  • and it doesn't call anything, it *gets* a reference to the next class; you can then call a method on it. – kindall Oct 28 '16 at 17:49

1 Answers1

1

The super() is literally a call to a method from the super class. In your example, the call to the update method from Avg class will first execute exactly the update method from the Std class with the vect and label parameters you passed in this line super(Avg, self).update(vect, label). Then, it will run the rest of the code you wrote after the super call.

Your Avg update method is equivalent to

class Avg(Std):
    def __init__(self):
         super(Avg, self).__init__()
         self.U = defaultdict(int)
         self.beta = 0

    def update(self, vect, label):
         self.bias += label
         for k, v in vect.items():
             self.W[k] += v * label

         self.beta += label * self.count
         for k, v in vect.items():
             self.U[k] += v * label * self.count
vribeiro
  • 161
  • 6