问题在
询问如何在 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 进行算术运算,我想这等同于说我想要 a
和 b
表现得完全像 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/