|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
dynamic variable declaration
hi ,
how can i declare variables dynamically? for example , in php i can do $var_num = 1; ${'var'.$var_num} = 5; so i get $var1 = 5 how can i do that in python? thanks ![]() |
|
#2
|
|||
|
|||
|
If I understood what you wanted, this can be done with:
Code:
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
|
|
#3
|
|||
|
|||
|
yes, that's what i need , thanks man
![]() |
|
#4
|
|||
|
|||
|
The solution that percivall gave will set an attribute on an object, as he said. To create a local or global variable (as in your PHP example) you can use the builtin functions locals() and globals(), which will return the dictionaries used for those namespaces. If you are in the top level namespace (i.e. outside of a function or class) then the two are equivalent.
The Python code corresponding to your example is: Code:
>>> var_num = 1 >>> globals()['var%s' % var_num] = 5 >>> var1 5 However the docs warn that modifying the locals() dictionary may not always work and should be avoided. It worked OK when I tested it, but may fail in some circumstances. An alternative that will always work is to use exec: Code:
>>> exec 'var%s = 23' % var_num >>> var1 23 Dave - The Developers' Coach |
|
#5
|
|||
|
|||
|
I said:
Quote:
After a little more experimenting and research, I have found that modifying locals() works ok at the top level namespace since it then locals() and globals() are the same. Inside a function locals() returns a copy of the namespace, so any changes to it do not affect the local variables: Code:
>>> var1 = 0 >>> def fn(): ... var_num = 1 ... locals()['var%s' % var_num] = 6 ... print var1 ... >>> fn() 0 so use either globals() or exec, depending on your requirements. Dave - The Developers' Coach |
|
#6
|
|||
|
|||
|
A better solution is, of course, to not do this at all but instead to use a list of variables.
|
|
#7
|
||||
|
||||
|
I agree with Strike here although the topic itself is very intersting - i saw a similar question in the perl forum ages ago and the recomendation there was also to use an array (list) - the best way to go IMO.
Mark. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > dynamic variable declaration |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|