gpt4 book ai didi

python - 为什么我的类实例是 int 类型(我无法访问它的属性)?

转载 作者:行者123 更新时间:2023-12-01 04:51:46 25 4
gpt4 key购买 nike

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

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 类型,并且我不知道如何处理该错误。

最佳答案

您正在类里面调用 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 参数,因为该方法未绑定(bind)。

您无法创建该类的实例,因为您没有提供 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()!

关于python - 为什么我的类实例是 int 类型(我无法访问它的属性)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28277370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com