【发布时间】:2010-05-14 16:05:43
【问题描述】:
问题
询问如何在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 类以允许这样做有任何想法吗?
感谢您的建议!
【问题讨论】: