python - 我可以创建一个行为类似于不可变( float )的类吗?

标签 python immutability inheritance

我有一个计算移动平均线的类(class),这可能会有所改进。平均窗口的大小必须是灵活的。 它目前通过设置窗口的大小然后发送更新来工作:

twoday = MovingAverage(2)    # twoday.value is None
twoday = twoday.update(10)   # twoday.value is None
twoday = twoday.update(20)   # twoday.value == 15
twoday = twoday.update(30)   # twoday.value == 25

我认为如果它能像这样工作会很酷:

twoday = MovingAverage(2)    # twoday is None
twoday += 10                 # twoday is None
twoday += 20                 # twoday == 15
twoday += 30                 # twoday == 25

这是愚蠢的吗? 可能吗?

最佳答案

您可以 emulate numeric types通过添加诸如 __add__() 之类的方法,它完全可以满足您的需求。

只需添加方法如

def __iadd__(self, other):
    self.update(other)
    return self

def __add__(self, other):
    return self.value + other

def __str__(self):
    return str(self.value)

您目前拥有的。

如果你想接近 float 的作用,你可以添加如下方法

def __float__(self):
    return self.value

def __radd__(self, other):
    return other + self.value

(后者为您提供了执行 somevalue + twoday 并获得预期值的方法)

__mul__/__rmul__,同div,等等。您唯一的特例可能是上面提到的 __iadd__()

关于python - 我可以创建一个行为类似于不可变( float )的类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736191/

相关文章:

python - 在 sqlalchemy 中对相同的声明性基础使用不同的模式

python - 可以从列表理解中返回两个列表吗?

scala - Scala 中的图遍历

C++ 将强类型基类与 CRTP 和返回值类型推导混合

python - 测试调用重写方法的类中的方法

c# - 如何将 IList<T1> 分配给 IList<T2>,其中 T1 是 T2 的子类型?

python - 如何在 Python 中记录类型参数?

python - Twython 的 Twitter 限制为 140 个字符

scala - 带有 var 的不可变映射或带有 val 的可变映射?

java - java中功能接口(interface)实例的相等性