Dynamic Variable name Assignment
You need to dynamically generate variables when using Tkinter, such as dynamically generating VAR1...VAR10 variables
- Using exec to dynamically assign values
exec
In Python3 is a built-in function that supports the dynamic execution of Python code.
Example:
In [1]: for i in range(5): ...: exec(‘var{} = {}‘.format(i, i)) ...:In [2]: print(var0, var1, var2, var3 ,var4)0 1 2 3 4
- Using namespaces to dynamically assign values
In the Python namespace, store the variable name and value in the dictionary.
You can locals()
globals()
get the local namespace and the global namespace, respectively, by using the function.
Example
In [2]: names = locals()In [3]: for i in range(5): ...: names[‘n‘ + str(i) ] = i ...:In [4]: print(n0, n1, n2, n3, n4)0 1 2 3 4
- The properties of a class object that uses dynamic variables in a class are stored in the property
__dict__
. __dict__
is a dictionary, the key is the property name, and the value corresponds to the value of the property.
In [1]: class Test_class(object): ...: def __init__(self): ...: names = self.__dict__ ...: for i in range(5): ...: names[‘n‘ + str(i)] = i ...:In [2]: t = Test_class()In [3]: print(t.n0, t.n1, t.n2, t.n3, t.n4)0 1 2 3 4
Calling dynamic variables
In fact, for repetitive variables, we don't normally call variables like this: var0, var1, var2, var3 ,var4....varN
you can use the following method to invoke variables dynamically
First define the following variables:
In [1]: for i in range(5): ...: exec(‘var{} = {}‘.format(i, i)) ...:In [2]: print(var0, var1, var2, var3 ,var4)0 1 2 3 4
Using the EXEC function
Similarly, you can use the exec
call variable
In [3]: for i in range(5): ...: exec(‘print(var{}, end=" ")‘.format(i)) ...:0 1 2 3 4
Using namespaces
Because the command space locals()
and globals()
all return a dictionary, use the dictionary get
method to get the value of the variable
In [4]: names = locals()In [5]: for i in range(5): ...: print(names.get(‘var‘ + str(i)), end=‘ ‘) ...:0 1 2 3 4
Python dynamic variable name definition and invocation