anything like C++ references?
Erik Max Francis
max at alcyone.com
Sat Jul 12 19:09:16 EDT 2003
Tom Plunket wrote:
> Is there any way to do references like this in Python? It'd be
> like this, though clearly this doesn't change the thing I want it
> to change:
Hi, Tom.
There's no builtin support for this in Python, but you can do it
yourself easily enough. Pass in a mutable container, and then twiddle
the object you want inside it.
>>> def change(val):
... val[0] += 1
...
>>> v = [0]
>>> change(v)
>>> v
[1]
I'm a strong believer in writing self-documenting code, so in a case
like this I write a (trivial) class that makes my intent crystal clear:
>>> class Container:
... def __init__(self, value=None): self.value = value
... def get(self): return self.value
...
>>> class Container:
... def __init__(self, value=None): self.value = value
... def get(self): return self.value
... def set(self, value): self.value = value
...
>>> def change(container):
... container.set(container.get() + 1)
...
>>>
>>> c = Container(0)
>>> change(c)
>>> c.get()
1
--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ Winners are men who have dedicated their whole lives to winning.
\__/ Woody Hayes
More information about the Python-list
mailing list