理解python中的子类

时间:2015-09-30 16:29:46

标签: python

我是python的新手,我一直在线观看一些教程,因为我想使用我发现的python开源库来处理一个项目。

我知道可以像这样在python中进行继承

class Parent:
    def print(self):
        pass

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

然而,当我在我的开源库中查看一些代码时,我看到了类似的东西。

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

看看这段代码,我想知道class MyStrategy(strategy.BacktestingStrategy)暗示了什么。我会理解它是否只在那里说策略,因为这意味着MyStrategy类正在从策略中获取。另外,我不明白这句话strategy.BacktestingStrategy.__init__(self, feed)暗示了什么?

我将不胜感激。

2 个答案:

答案 0 :(得分:3)

strategy是您导入的模块:

from pyalgotrade import strategy

现在strategy.BacktestingStrategy是位于模块strategy内的一个类。该类将用作MyStrategy的超类。

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

此函数__init__(self, feed, instrument)MyStrategy的构造函数,只要您创建此类的新实例,就会调用该函数。

它覆盖了其超类的__init__方法,但它仍然想要执行那个旧代码。因此,它使用

调用其超类的构造函数方法
strategy.BacktestingStrategy.__init__(self, feed)

在这一行strategy.BacktestingStrategy是超类,__init__是它的构造方法。您将包含当前对象实例的参数self显式地作为第一个参数传递,因为该方法直接从超类调用,而不是从它的实例调用。

答案 1 :(得分:1)

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

因为策略是一个模块(文件/或某些情况下的文件夹)而不是类,所以你无法继承它...

相关问题