Python 尝试使用类输出列表

Python 尝试使用类输出列表,python,class,Python,Class,我试图获取价格的移动平均值,但在我的moving_average类中不断得到一个属性错误: 'Moving_Average' object has no attribute 'days' 以下是我所拥有的: class Moving_Average: def calculation(self, alist:list,days:int): m = self.days prices = alist[1::2] average = [0]*

我试图获取价格的移动平均值,但在我的
moving_average
类中不断得到一个属性错误:

'Moving_Average' object has no attribute 'days'
以下是我所拥有的:

class Moving_Average:

    def calculation(self, alist:list,days:int):
        m = self.days
        prices = alist[1::2]
        average = [0]* len(prices)
        signal = ['']* len(prices)
        for m in range(0,len(prices)-days+1):
            average[m+2] = sum(prices[m:m+days])/days
            if prices[m+2] < average[m+2]:
                signal[m+2]='SELL'
            elif prices[m+2] > average[m+2] and prices[m+1] < average[m+1]:
                signal[m+2]='BUY'
            else:
                signal[m+2] =''
        return average,signal

def print_report(symbol:str,strategy:str):
        print('SYMBOL: ', symbol)
        print('STRATEGY: ', strategy)
        print('Date            Closing        Strategy        Signal')


def user():
    strategy = '''
    Which of the following strategy would you like to use?
    * Simple Moving Average [S]
    * Directional Indicator[D]

    Please enter your choice: '''

    if signal_strategy in 'Ss':
        days = input('Please enter the number of days for the average')
        days = int(days)
        strategy = 'Simple Moving Average {}-days'.format(str(days))
        m = Moving_Average()
        ma = m.calculation(gg, days)
        print(ma)
输出应该如下所示:

 Date       Price      Average      Signal
2013-10-01   60.0                       
2013-10-02   60.0       60.00         BUY

您引用的是
days
,它是
calculation
函数的参数,而不是类的实例变量。你不需要使用
self.days
来访问它,只要使用
m=days

移动平均值类就可以了。打印功能不是它的一部分。为什么这是一个
?请修复缩进。我可以猜测
计算
应该是该类的一种方法,但是
打印报告
——它比
计算
缩进得多——是顶级函数吗?这是
如果
应该在
print\u report
中,还是模块级代码?print\u report()和user()在不同的模块中。此行
m=self.days
不起任何作用,因为一旦到达for循环,
m
就会被覆盖。事实上,删除它根本不会影响脚本。嗨,ramirez…如果我这样做,我会在计算函数中得到以下错误:User_interface(),ma=m.calculation(gg,days),average[m+2]=sum(prices[m:m+days])/days。。。。TypeError:+:“int”和“str”的操作数类型不受支持,这似乎是代码在其他地方出现的另一个问题。我在你发布的代码中没有看到这一部分。更新您的问题。@captainmorgan:当您的代码被破坏时,修复一个bug通常只会暴露下一个bug。这并不意味着修复是错误的。这个答案解决了您所问的问题,并解释了为什么会这样做。事实上,它并没有神奇地修复您的所有其他代码,即使是我们没有看到的部分,但这并不意味着它不是一个完整的答案。@ramirez我认为问题在于计算函数。一旦您意识到Python错误消息是有用的,那么Python错误消息将提供大量信息。它告诉你你有一个
int
str
,你正试图把它们加在一起。您的列表中有什么?串?
 Date       Price      Average      Signal
2013-10-01   60.0                       
2013-10-02   60.0       60.00         BUY