在 Python 中模拟指针 [英] Simulating Pointers in Python

查看:23
本文介绍了在 Python 中模拟指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将内部语言 (ihl) 交叉编译为 Python.

I'm trying to cross compile an in house language(ihl) to Python.

ihl 的特性之一是指针和引用的行为与您对 C 或 C++ 的期望相同.

One of the ihl features is pointers and references that behave like you would expect from C or C++.

例如你可以这样做:

a = [1,2];  // a has an array 
b = &a;     // b points to a
*b = 2;     // derefernce b to store 2 in a
print(a);   // outputs 2
print(*b);   // outputs 2

有没有办法在 Python 中复制此功能.

Is there a way to duplicate this functionality in Python.

我应该指出,我认为我混淆了一些人.我不想在 Python 中使用指针.我只是想从那里的 Python 专家那里了解一下,我应该生成什么 Python 来模拟我上面展示的情况

我的 Python 不是最好的,但到目前为止我的探索没有产生任何有希望的结果:(

My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(

我应该指出,我们正在寻求从我们的 ihl 转向一种更通用的语言,因此如果有人可以建议另一种可能更合适的语言,我们就不会真正与 Python 联系在一起.

I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.

推荐答案

这可以显式完成.

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, 2])
b = a
print(a.get())  # => [1, 2]
print(b.get())  # => [1, 2]

b.set(2)
print(a.get())  # => 2
print(b.get())  # => 2

这篇关于在 Python 中模拟指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆