1

我在 Python 中创建了一个只有抽象方法的类,然后实现了该类中的所有方法BasicMR(片段中并非所有代码BasicMR都存在,但该方法test_stationary()在内部被调用self.generate_positions()):

class Strategy(object):
    __metaclass__=ABCMeta

    @abstractmethod
    def generate_positions(self):
        raise NotImplementedError("You must implement generatePositions()!")

    @abstractmethod
    def get_positions(self):
        raise NotImplementedError("You must implement getPositions()!")


class BasicMR(Strategy):
    def __init__(self, security, lookback=30):
        self.__securities = []
        self.__securities = security   # it could be either one security or a list of security objects
        self.__positions = self.generate_positions()

    def test_stationary(self, lb=30):
        if not isinstance(self.__securities, list):
            securities = [self.__securities]
        else:
            securities = self.__securities
        prices = [one_stock.get_prices(lb) for one_stock in securities]  # list comprehension
        results = [ts.adfuller(price_series, regression="c", autolag='AIC') for price_series in prices]
        simple_results = [BasicMR.simplify_adf_results(result[1], result[0], result[4]) for result in results]
        if len(simple_results) == 1:
            return simple_results[0]
        else:
            return simple_results

    def generate_positions(self, long_only=False, time_frame=20, max_holding_period = 20):
        result = []
        names = []
        # HERE IS SOME CODE
        return [names, result]

    def get_positions(self):
        return self.__positions

但是,当我创建 的实例时BasicMR(),我在这一行得到一个错误:

if not isinstance(self.__securities, list):

错误:

AttributeError: 'int' object has no attribute '_BasicMR__securities'

不知何故,我的 BasicMR 类实例被识别为 type int,我不知道如何处理该错误。

4

2 回答 2

2

您正在test_stationary 上课

>>> BasicMR.test_stationary(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 20, in test_stationary
AttributeError: 'int' object has no attribute '_BasicMR__securities'

42这作为参数传入,self因为该方法未绑定。

您无法创建该类的实例,因为您没有提供具体的实现generate_positionsget_positions但是:

>>> BasicMR([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 17, in __init__
  File "<string>", line 6, in generate_positions
NotImplementedError: You must implement generatePositions()!
于 2015-02-02T12:11:05.033 回答
0

我终于找到了问题的根源。在generate_positions()我调用实例方法的方法中,就好像它是一个类方法一样,而不是写

stationarity_checked_securities = self.test_stationary(time_frame)

我有:

stationarity_checked_securities = BasicMR.test_stationary(time_frame)

test_stationary()定义为:

def test_stationary(self, lb=30):
    #some code here

也就是说,它不是一个类方法,但我把它当作是。最后,我的 bug 看起来很简单,但是我被错误文本弄糊涂了(我是 Python 新手,我不明白为什么我的类实例int object在错误中被称为“”。

于 2015-02-02T15:32:59.833 回答