[Tutor] Variables of Variables

John Fouhy john at fouhy.net
Thu Jan 18 22:55:55 CET 2007


On 19/01/07, Tino Dai <tinoloc at gmail.com> wrote:
> Hi Everybody,
>
>      Is there a way to do variables of variables in python. For example in
> perl:
>
> $foo = 'bar'
> $$foo = '5'
>
> and $bar will have a value of 5. I have been search high and low for a
> simple way to do this in python?

In the context of objects, you can do this with setattr() and getattr().

eg:
>>> class MyClass(object):
...  pass
...
>>> m = MyClass()
>>> m.a = 3
>>> getattr(m, 'a')
3
>>> m.b
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'MyClass' object has no attribute 'b'
>>> setattr(m, 'b', 7)
>>> m.b
7
>>> delattr(m, 'b')
>>> m.b
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'MyClass' object has no attribute 'b'

Obviously, anywhere you see a string in that example, you could
substitute a variable with a string value.

You can't do this if you aren't working with objects.
(well, maybe you could if you used some black magic.. but you should
generally avoid that)

However, the other question you should ask yourself is: should you be
using a dictionary instead?  Rather than storing your data as
variables, you could store it in a dictionary.  Then you can
dynamically access data however you like..

-- 
John.


More information about the Tutor mailing list