'Will using super(type, instance) call the derived version of an embedded method?

If I instance a derived class:

class ContactReports(CleanUpReports):

    def do_batch(self, batchfile):
        super(CleanUpReports,self).do_batch(batchfile)

    def extend(self, rpt):
        self.specialized_processing(rpt)

But the parent class also has an extend function defined like so:

class CleanUpReports:
    ...

    def do_batch(self, batchfile):
        with open(batchfile) as f:
             for rpt in f:
                self.extend(rpt)

    def extend(self, rpt):
       self.default_processing(rpt)

Will the delegated do_batch() method call the parent version of extend() or the derived instance version of extend()?

How can I ensure the delegated version of do_batch() calls the derived version of extend()?



Solution 1:[1]

The short answer is that it will call the implementation of the derived or child class (ContactReports in this case).

To verify this I am going to do a small test simplifying the code a little bit and also add a new method called `` in the parent class:

class CleanUpReports:
  def do_batch(self):
    print("do_batch from parent class")

  def extend(self):
    print("extend from parent class")

  def func_only_in_parent(self):
    print("func_only_in_parent from parent class")

class ContactReports(CleanUpReports):
  def do_batch(self):
    print("do_batch from child class")
  
  def extend(self):
    print("extend from child class")

When instantiating an object from the child class, you get this:

child_instance = ContactReports()
child_instance.do_batch()
child_instance.extend()
child_instance.func_only_in_parent()

Output:

>>> do_batch from child class
>>> extend from child class
>>> func_only_in_parent from parent class

And as an addition, if you instantiate an object from the parent class you get this.

parent_instance = CleanUpReports()
parent_instance.do_batch()
parent_instance.extend()
parent_instance.func_only_in_parent()

Output:

>>> do_batch from parent class
>>> extend from parent class
>>> func_only_in_parent from parent class

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kloster Matias