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

查看:107
本文介绍了在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++.

例如,您可以执行以下操作:

For instance you can do this:

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不是最好的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天全站免登陆