Python 等价于指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2065105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python equivalent of pointers
提问by random guy
In python everything works by reference:
在 python 中,一切都是通过引用来工作的:
>>> a = 1
>>> d = {'a':a}
>>> d['a']
1
>>> a = 2
>>> d['a']
1
I want something like this
我想要这样的东西
>>> a = 1
>>> d = {'a':magical pointer to a}
>>> d['a']
1
>>> a = 2
>>> d['a']
2
What would you substitute for magical pointer to aso that python would output what I want.
你会用什么来代替指向 a 的神奇指针,以便 python 输出我想要的。
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)
我很欣赏通用的解决方案(不仅适用于上述带有自变量的字典示例,还适用于其他集合和类/实例变量)
回答by danben
What about a mutable data structure?
可变数据结构呢?
>>> a = mutable_structure(1)
>>> d = {'a':a}
>>> d['a']
1
>>> a.setValue(2)
>>> d['a']
2
An implementation might look like
一个实现可能看起来像
class mutable_structure:
def __init__(self, val):
self.val = val
def __repr__(self):
return self.val
回答by Johann Hibschman
The standard solution is to just use a list; it's the easiest mutable structure.
标准的解决方案是只使用一个列表;这是最简单的可变结构。
a = [1]
d = {'a': a}
a[0] = 2
print d['a'][0]
回答by Joakim Lundborg
This is because 1 is a immutable datatype in python, i.e. you can't change the value of it.
这是因为 1 在 python 中是不可变的数据类型,即你不能改变它的值。
To make it work like a pointer, you need a mutable datatype as storage, which you can do yourself with a class definition
为了使它像指针一样工作,您需要一个可变数据类型作为存储,您可以使用类定义自己完成
class Mutable(object):
pass
a = Mutable()
a.value = 1
d = {'a':a}
a.value = 3
d['a'].value
equals 3 at this point.
d['a'].value
此时等于 3。
If you really want, you can overload operators etc. so that you get the same semantics as for normal integers, but I'd suggest you instead take a look at some functional programming patterns to see why immutable types are nice.
如果您真的想要,您可以重载运算符等,以便获得与普通整数相同的语义,但我建议您改为查看一些函数式编程模式,以了解为什么不可变类型很好。
回答by jcdyer
If you're working in a class you could do something like this:
如果你在课堂上工作,你可以做这样的事情:
class DRefsA(object):
a = 4
@property
def d(self):
return self.a
@d.setter
def d(self, value):
self.a = value
回答by coder
a bit late to the party but heres a solution that works with any data type with lamda
聚会有点晚了,但这是一个适用于任何数据类型和 lamda 的解决方案
a = 1
d = {'a': lambda : a}
print(d['a']()) #output 1
a = 2
print(d['a']()) #output 2