gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:11:16 25 4
gpt4 key购买 nike

问题在

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com