有什么好方法可以让不同的变量引用相同的值,同时仍然允许直接操作,例如*
上的值?
所需代码的示例能够执行以下操作:
a = <Reference to integer 2>
b = a
print(a * b) # Should show 4
<a update (not with assign using =) with reference to integer 3>
print(a * b) # Should show 9
一个不太理想的解决方案是为值使用一个容器,如命名空间、列表、字典等,但这需要引用下面的 .value
之类的属性,因此不太理想:
import types
a = types.SimpleNamespace(value = 2)
b = a
print(a.value * b.value) # Should show 4
a.value = 3
print(a.value * b.value) # Should show 9
封装值的好方法是什么,这样直接操作仍然是可能的?
最佳答案
您可以创建一个覆盖乘法运算的类。
class Reference:
def __init__(self, value):
self.value = value
def __mul__(self, other):
return Reference(self.value * other.value)
这将允许您直接将引用彼此相乘。例如,Reference(3) * Reference(4)
生成 Reference(12)
。
您可能想要覆盖 __rmul__
以及所有其他数值运算。 numbers
中的抽象类可能对确保您不会忘记任何东西很有用。
关于python - 如何让不同的变量引用相同的值,同时仍然允许直接操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036609/