如何使不同的变量引用相同的值,同时仍允许直接操作?

Mor*_*mer 3 python python-3.x

什么是使不同变量引用相同值的好方法,同时仍允许直接操作,例如*在值上?

所需代码的示例能够执行以下操作:

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
Run Code Online (Sandbox Code Playgroud)

一个不太理想的解决方案是使用容器作为值,如命名空间,列表,字典等,但这需要引用.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
Run Code Online (Sandbox Code Playgroud)

封装值的好方法是什么,所以直接操作仍然可行?

Kev*_*vin 5

您可以创建一个覆盖乘法运算的类.

class Reference:
    def __init__(self, value):
        self.value = value
    def __mul__(self, other):
        return Reference(self.value * other.value)
Run Code Online (Sandbox Code Playgroud)

这将允许您直接相互引用参考.例如,Reference(3) * Reference(4)生产Reference(12).

您可能还想覆盖__rmul__所有其他数值运算.抽象类numbers可能证明有用,以确保您不会忘记任何.