首页 > 解决方案 > 在 Python 中使用什么方法来返回对象的属性?

问题描述

我正在尝试创建一个“CumulativeMovingAverage”类。这就是我所做的:

class CumulativeMovingAverage():
    cma = None
    n = 0
    def add(self, *args):
        if self.cma is None:
            self.cma = args[0]

        else:
            self.cma = (args[0] + self.n*self.cma) / (self.n+1)
        self.n += 1
        return None

    def __call__(self):
        return self.cma

它是这样工作的:

a = CumulativeMovingAverage()
a.add(2)
a.add(4)
a.cma ==> 3
a() ==> 3

我想覆盖一个 dunder 方法,这样

a ==> 3 并且

b = a + 100
b ==> 103

也就是说,不必用括号调用 a 。可能吗?我应该覆盖什么?

标签: python

解决方案


推荐阅读