changing a var by reference of a list
Larry Bates
larry.bates at websafe.com
Tue May 8 09:29:31 EDT 2007
Jorgen Bodde wrote:
> Hi,
>
> I am trying to simplify my code, and want to automate the assigning of
> variables I get back from a set. I was thinking of putting the
> variables I want changed in a list:
>
> L = [self._varA, self._varB ]
>
> self._varA is a variable I want to change when I pass L to a function.
> I know doing this;
>
> L[0] = 12
>
> Will replace the entry self._varA with 12, but is there a way to
> indirectly change the value of self._varA, through the list, something
> like a by-reference in C++ or a pointer-pointer?
>
> With regards,
> - Jorgen
You can make self._varA and self._varB instances of a class and
assign a value. Not tested.
class _var:
pass
self._varA=_var()
self._varB=_var()
L=[self._varA, self._varB]
then in function (or method of a class instance):
L[0].value=12
Another way is to use a class to pass everything:
class _vars:
def __init__(self, vars=None):
if vars is not None:
for varname, value in vars.items():
setattr(self, varname, value)
return
vars=_vars({'_varA': 0, '_varB': 0})
Then you can access:
vars._varA
vars._varB
-Larry
l
More information about the Python-list
mailing list