Dynamic Variable Name Assignment
When using tkinter, it is necessary to dynamically generate variables, such as dynamically generating var1...var10 variables.
Using exec for Dynamic Assignment
exec is a built-in function in python3, which supports dynamic execution of Python code.
Using exec for Dynamic Assignment
exec is a built-in function in python3, which supports dynamic execution of Python code.
Example
... exec('var{} = {}'.format(i, i))
...
>>> print(var0, var1, var2, var3 ,var4)
0 1 2 3 4
>>>
Dynamic Assignment Using Namespace
In Python's namespace, variable names and values are stored in a dictionary. You can use the locals() and globals() functions to obtain the local namespace and global namespace respectively.
Example
>>> for i in range(5):
... names['n' + str(i) ] = i
...
>>> print(n0, n1, n2, n3, n4)
0 1 2 3 4
>>>
Using Dynamic Variables in Classes
The attributes of Python class objects are stored in __dict__. __dict__ is a dictionary, with keys being attribute names and values corresponding to attribute values.
Example
0 1 2 3 4
>>> class Test_class(object):
... def __init__(self):
... names = self.__dict__
... for i in range(5):
... names['n' + str(i)] = i
...
>>> t = Test_class()
>>> 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 generally don't call variables this way, such as: var0, var1, var2, var3, var4....varN. We can use the following method to dynamically call variables.
First define the following variables:
Example
... exec('var{} = {}'.format(i, i))
...
>>> print(var0, var1, var2, var3 ,var4)
0 1 2 3 4
Using the exec Function
Similarly, you can use exec to call variables
Example
... exec('print(var{}, end=" ")'.format(i))
...
0 1 2 3 4
Using Namespace
Because both locals() and globals() in the namespace return a dictionary, use the dictionary's get method to obtain variable values.
Example
>>> for i in range(5):
... print(names.get('var' + str(i)), end=' ')
...
0 1 2 3 4
Original address: https://www.cnblogs.com/technologylife/p/9211324.html