我在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类实例被识别为类型int
,我不知道如何处理该错误。
答案 0 :(得分: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_positions
和get_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()!
答案 1 :(得分:0)
我终于找到了问题的根源。在generate_positions()
方法中,我调用了实例&#39;方法好像它是一个类方法,而不是写
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的新手,我无法理解为什么我的类实例被称为&#34; {{ 1}}&#34;错误。