user1010101
user1010101

Reputation: 1658

Understanding subclasses in python

I am quite new to python and I have been watching some tutorials online because I want to work on a project using python open source library I found.

I know that it is possible to do inheritance in python like this

class Parent:
    def print(self):
        pass

class Child(Parent):
    def print(self):
        pass

However when i was looking at some code in my open source library I saw something like this.

from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__instrument = instrument

Looking at this piece of code I am wondering what does class MyStrategy(strategy.BacktestingStrategy) imply. I would understand if it only said strategy in there because that would mean MyStrategy class is inherting from strategy. Also I do not understand what this linestrategy.BacktestingStrategy.__init__(self, feed) is implying?

I would appreciate any explanation.

Upvotes: 1

Views: 110

Answers (2)

Byte Commander
Byte Commander

Reputation: 6746

strategy is the module you imported with:

from pyalgotrade import strategy

Now strategy.BacktestingStrategy is a class located inside the module strategy. This class will used as superclass for MyStrategy.


def __init__(self, feed, instrument):
    strategy.BacktestingStrategy.__init__(self, feed)
    # ...

This function __init__(self, feed, instrument) is the constructor function of MyStrategy that will be called whenever you create a new instance of this class.

It overrides the __init__ method of its superclass, but it still wants to also execute that old code. Therefore it calls its superclass' constructor method using

strategy.BacktestingStrategy.__init__(self, feed)

In this line strategy.BacktestingStrategy is the superclass and __init__ is its constructor method. You pass the argument self containing the current object instance as first argument explicitly, because the method gets called from the superclass directly and not from an instance of it.

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 113988

strategy.BacktestingStrategy #this is the class that your MyStrategy class inherits , it is class BacktestingStrategy, located in strategy.py

strategy.BacktestingStrategy.__init__(self, feed)  # calls the parents constructor ... if the base class inherits from object you would typically do 

super().__init__(feed) # python 3 way of calling the super class

since strategy is a module (file/or in some cases folder) and not a class there is no way you could inherit from it ...

Upvotes: 1

Related Questions