让不同的变量引用相同的值,同时仍然允许对值进行直接操作(例如*
)的好方法是什么?你知道吗
所需代码的示例是能够执行以下操作:
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
不太理想的解决方案是为值使用容器,如namespace、list、dict等,但这需要引用下面的.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
封装值的好方法是什么,这样直接操作仍然是可能的?你知道吗
你想要的行为可以用一个类来模拟,尽管有点笨拙和不雅:
在这些运算符过载的情况下,将出现以下情况:
印刷品
我意识到如果你想引用不同的类型,这是相当麻烦的,因为你必须为每一个类型重载你需要的操作符,但是这是最接近于模拟指针的。你知道吗
或者,您可以在
reference
类中只包含get
、set
和__init__
,然后添加稍后需要的重载函数:以上打印
20
也许吧?你知道吗
您可以创建一个重写乘法运算的类。你知道吗
这将允许您直接将引用彼此相乘。例如,
Reference(3) * Reference(4)
产生Reference(12)
。你知道吗您可能需要重写} 中的抽象类可能对确保您不会忘记任何抽象类很有用。你知道吗
__rmul__
和所有其他数值运算。^{相关问题 更多 >
编程相关推荐