在__init__中调用的类方法与在类外部使用的相同函数的输出不相同



我敢肯定我在这里错过了类的工作方式,但基本上这是我的类:

import pandas as pd
import numpy as np
import scipy
#example DF with OHLC columns and 100 rows
gold = pd.DataFrame({'Open':[i for i in range(100)],'Close':[i for i in range(100)],'High':[i for i in range(100)],'Low':[i for i in range(100)]})
class Backtest:

def __init__(self, ticker, df):
self.ticker = ticker
self.df = df
self.levels = pivot_points(self.df)

def pivot_points(self,df,period=30):
highs = scipy.signal.argrelmax(df.High.values,order=period)
lows = scipy.signal.argrelmin(df.Low.values,order=period)
return list(df.High[highs[0]]) + list(df.Low[lows[0]])

inst = Backtest('gold',gold) #gold is a Pandas Dataframe with Open High Low Close columns and data
inst.levels # This give me the whole dataframe (inst.df) instead of the expected output of the pivot_point function (a list of integers)

问题是inst.levels返回整个DataFrame而不是函数pivot_points的返回值(应该是整数列表)

当我在这个类之外的同一个DataFrame上调用pivot_points函数时,我得到了我期望的列表

我期望在将pivot_points()函数赋值给self后得到它的结果。init中的而是得到了整个DataFrame

您必须将pivot_points()指定为self.pivot_points()

如果你不改变它,就不需要添加句点作为参数,如果你改变了,那就可以了

我不确定这是否有帮助,但这里有一些关于你的类的提示:

class Backtest:
def __init__(self, ticker, df):
self.ticker = ticker
self.df = df
# no need to define a instance variable here, you can access the method directly
# self.levels = pivot_points(self.df)
def pivot_points(self):
period = 30
# period is a local variable to pivot_points so I can access it directly
print(f'period inside Backtest.pivot_points: {period}')
# df is an instance variable and can be accessed in any method of Backtest after it is instantiated
print(f'self.df inside Backtest.pivot_points(): {self.df}')
# to get any values out of pivot_points we return some calcualtions
return 1 + 1
# if you do need an attribute like level to access it by inst.level you could create a property
@property
def level(self):
return self.pivot_points()

gold = 'some data'
inst = Backtest('gold', gold)  # gold is a Pandas Dataframe with Open High Low Close columns and data
print(f'inst.pivot_points() outside the class: {inst.pivot_points()}')
print(f'inst.level outside the class: {inst.level}')

结果如下:

period inside Backtest.pivot_points: 30
self.df inside Backtest.pivot_points(): some data
inst.pivot_points() outside the class: 2
period inside Backtest.pivot_points: 30
self.df inside Backtest.pivot_points(): some data
inst.level outside the class: 2

多亏了注释者Henry Ecker,我发现我在文件的其他地方定义了同名的函数,其中输出是df。修改后,我的原始代码按预期工作

最新更新