理解python中的子类

2024-09-27 18:07:35 发布

您现在位置: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)意味着什么?你知道吗

如能解释,我将不胜感激。你知道吗


Tags: 代码fromselfinitdeffeed开源pass
2条回答
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

由于strategy是一个模块(文件/或在某些情况下是文件夹)而不是一个类,因此您无法从中继承。。。你知道吗

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作为第一个参数显式传递,因为该方法直接从超类调用,而不是从它的实例调用。你知道吗

相关问题 更多 >

    热门问题