Dynamic Variable Name Definition and Invocation in Python
Category Programming Techniques
Dynamic Variable Assignment
When using tkinter, dynamic generation of variables is required, such as dynamically generating variables var1...var10.
Dynamic Assignment Using exec
The exec function in Python 3 is a built-in function that supports the dynamic execution of Python code.
Dynamic Assignment Using exec
The exec function in Python 3 is a built-in function that supports the dynamic execution of Python code.
Example
>>> for i in range(5):
... 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, which can be accessed using the locals() and globals() functions for local and global namespaces, respectively.
Example
>>> names = locals()
>>> 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 a Class
In Python, class object attributes are stored in the __dict__. __dict__ is a dictionary where the keys are attribute names and the values correspond to the values of the attributes.
Example
>>> print(n0, n1, n2, n3, n4)
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
Invoking Dynamic Variables
In fact, for repetitive variables, we generally do not invoke variables in this way, such as: var0, var1, var2, var3, var4...varN. The following methods can be used to dynamically invoke variables.
First, define the following variables:
Example
>>> for i in range(5):
... exec('var{} = {}'.format(i, i))
...
>>> print(var0, var1, var2, var3 ,var4)
0 1 2 3 4
Using the exec Function
Similarly, the exec function can be used to invoke variables.
Example
>>> for i in range(5):
... exec('print(var{}, end=" ")'.format(i))
...
0 1 2 3 4
Using the Namespace
Since both the local and global namespaces returned by locals() and globals() are dictionaries, the get method of the dictionary can be used to retrieve the value of the variable.
Example
>>> names = locals()
>>> for i in range(5):
... print(names.get('var' + str(i)), end=' ')
...
0 1 2 3 4
>
Original article link: https://www.cnblogs.com/technologylife/p/9211324.html
** Click to Share Notes
-
-
-