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

标签 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

一个不太理想的解决方案是为值使用一个容器,如命名空间、列表、字典等,但这需要引用下面的 .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/

相关文章:

python - 将元组的字符串数组转换为输入和输出

python - 确定类属性是否为只读数据描述符

python - 在Python中重新排列图像

python - 检查记录是否存在的最快方法

python - 从 pandas.df_dummies 返回的最优雅的方式

python - 当使用 .clamp 而不是 torch.relu 时,Pytorch Autograd 会给出不同的渐变

python - Google App Engine yaml 文件配置

Python pandas 如何通过内部编号获取某些值?

python - 检查序列是否包含非连续子序列的最快方法?

python - Tensorflow 变量未使用图间复制进行初始化