python - 在 Python 中模拟指针以进行算术运算

标签 python pointers

问题在

Simulating Pointers in Python

询问如何在 Python 中模拟指针在解决方案中有一个很好的建议,即做

class ref:
    def __init__(self, obj): self.obj = obj
    def get(self): return self.obj
    def set(self, obj): self.obj = obj

然后可以用来做例如

a = ref(1.22)
b = ref(a)

print a # prints 1.22
print b.get() # prints 1.22

可以修改该类,通过添加

来避免对打印语句使用get
def __str__(self): return self.obj.__str__()

然后,

print b # prints out 1.22

现在我希望能够用与 a 相同的方式对 b 进行算术运算,我想这等同于说我想要 ab表现得完全像 obj。有没有办法做到这一点?我尝试添加方法,例如

def __getattribute__(self, attribute): return self.obj.__getattribute__(attribute)
def __call__(self): return self.obj.__call__()

但无论如何,

的输出
print a + b

总是

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    print a + b
TypeError: unsupported operand type(s) for +: 'instance' and 'instance'

有没有人对如何修改 ref 类以允许这样做有任何想法?

感谢您的任何建议!

最佳答案

+ 运算符通过左操作数的 __add__() 方法或右操作数的 __radd__() 方法实现.

Here .

关于python - 在 Python 中模拟指针以进行算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835639/

相关文章:

c++ - 与返回硬编码字符串文字的函数一起存储的字符串在哪里?

c - C 编译器内部如何处理数组和指针类型? ( int *a; 与 int a[]; )

C::在函数中转换指针会丢失数据吗?

pointers - 如何在 Golang 中动态取消引用指针

python - 如何通过 python 脚本打开多个 cmd session ?

python - 评估 nans 切片大小

printing - Python 解释器中的 `>>> some_object` 和 `>>> print some_object` 有什么区别?

python - 过滤字符串列表,忽略其他项的子字符串

python - 查找最后一个非零元素 3D 数组 - numpy 数组

C:如何将结构添加到指针数组