Passing address of variables...
Joshua Macy
l0819m0v0smfm001 at sneakemail.com
Sat Sep 15 15:54:39 EDT 2001
Since variables in Python always contain references, most of the time
you don't have to do anything special:
>>> a = [0, 1]
>>> def f(x):
... x[1] += 1
...
>>> f(a)
>>> a
[0, 2]
>>> a = {'spam' : 0 }
>>> def g(x):
... x['spam'] += 1
...
>>> g(a)
>>> a['spam']
1
>>> class A:
... def __init__(self):
... self.x = 0
...
>>> a = A()
>>> def h(x):
... x.x += 1
...
>>> h(a)
>>> a.x
1
The problem you might run into in translating the way you think about,
say, C, into Python is that this doesn't appear to work for things like
integers, strings, and tuples, since they're immutable. x += 1 when x
is an integer will lose the reference to the first integer and replace
it with a reference to a new integer. If you want this kind of
side-effect, you have to learn to start wrapping the variables you want
in mutable types and changing the contents of that type--which is the
more Pythonic (and OO) way to do it anyway.
>>> b = [0, 1]
>>> a = b
>>> f(a)
>>> b
[0, 2]
>>> f(b)
>>> a
[0, 3]
Of course, another way to look at it is that you should generally try to
reduce such side effects anyway, so that your C example would be better
rewritten and translated as
>>> def something(x):
... x += 1
... return x
...
>>> x = 0
>>> x = something(x)
>>> x
1
Joshua
Adonis Vargas wrote:
> how am i able to pass the address of a variable to another variable have it
> affected by
> change(s)?
>
> i.e. like in C/C++ you have:
>
> int something(int &blah)
> {
> blah++;
> }
>
> int x=0;
> something(x)
> print x // returns 1
>
> just a rough idea; can this be done in Python?
>
> any help would greatly be appreciated.
>
> Adonis
>
>
>
More information about the Python-list
mailing list