等效于Python的指针 [英] Python equivalent of pointers

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

问题描述

在python中,所有内容均可通过引用进行工作:

In python everything works by reference:

>>> a = 1
>>> d = {'a':a}
>>> d['a']
1
>>> a = 2
>>> d['a']
1

我想要这样的东西

>>> a = 1
>>> d = {'a':magical pointer to a}
>>> d['a']
1
>>> a = 2
>>> d['a']
2

您将用什么代替指向一个的神奇指针,以便python输出我想要的内容.

What would you substitute for magical pointer to a so that python would output what I want.

我会喜欢一些通用的解决方案(不仅适用于上面的字典示例中具有自变量的示例,而且适用于其他集合和类/实例变量的示例)

I would appreciate general solutions (not just for the above dictionary example with independent variables, but something that would work for other collections and class/instance variables)

推荐答案

可变数据结构如何?

>>> a = mutable_structure(1)
>>> d = {'a':a}
>>> d['a']
1
>>> a.setValue(2)
>>> d['a']
2

一个实现可能看起来像

class mutable_structure:
  def __init__(self, val):
    self.val = val

  def __repr__(self):
    return self.val

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

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