Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the behavior of an inherited function in Python

Let's say we have the following classes:

class Base(object):

    def load(self):
        # do logic A

        # do logic B

class Child(Base):

    def load(self):
        # do logic C

I know decorators can be used to extend function behavior in Python but I don't know how I can apply it in my case. When Child's load() is called, how can I get the following code executions in this order?:

logic A

logic C

logic B

What I don't want to do

class Base(object)

    def logicA()
       pass

    def logicB()
       pass

    def load()
       pass

class Child(Base):

    def load(self):
        super.logicA()

        # do logic C

        super.logicB()

I just want to code up logic C, without having to explicitly call logic A and B

like image 845
lambda Avatar asked Mar 03 '15 01:03

lambda


People also ask

How do you extend a class through inheritance in Python?

In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism.

How do you extend in Python?

extend() is Python's built-in function. It iterates over the specified iterable and appends its elements to the end of the current list. The list. extend() method is equivalent to list[len(list):] = iterable (appends the elements of the iterable after the list's last element).

Which keyword is used to extend a class from another in Python?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another.

What does super () __ Init__ do in Python?

When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.


1 Answers

You mean something like this:

class Base(object):

    def load(self):
        print('do logic A')
        print('do logic B')


class Child(Base):

    def load(self):
        super().load()
        print('do logic C')


c = Child()
c.load()   

This will print:

do logic A
do logic B
do logic C

The only other way I can think of is this one:

class Base(object):

    def load(self):
        print('do logic A')
        self.new_logic() # call new logic from child class, if exist.
        print('do logic B')

    def new_logic(self):
        # overwrite this one in child class 
        pass


class Child(Base):

    def new_logic(self):
        print('do logic C')


c = Child()
c.load()   

This prints:

do logic A
do logic C
do logic B
like image 178
Marcin Avatar answered Oct 17 '22 08:10

Marcin