我是初学。在python3中,使用
for i in range(3):
locals()['part' + str(i)] = i
print(part0)
print(part1)
print(part2)
能够得到三个动态生成的变量part0,part1和part2
但是把上面代码包含到一个函数中
def Main():
for i in range(3):
locals()['part'+str(i)] = i
print(part0)
print(part1)
print(part2)
Main()
却会报错,说变量part0没有被定义呢?
Look at a piece of code first
By now you should understand that locals actually means the current scope.
Then let’s execute a piece of code
The output is:
At this time, the variable
test
is dynamically added. But note that the variable definition is added using locals() in the outermost layer, that is, the global scope.So why do you get an error when dynamically adding variables through locals() in your code?
Note: Searching the local namespace here does not search locals(), so adding variables in locals() of the local space will not be searched by python. In fact, in the local scope, locals is a readable function to output the variables defined in the local scope. Python does not read locals() internally to find the variable name, and it is not feasible to change the variable value through locals. , the code is as follows
This explains why
part0
undefined errors are reported in your code.So, how can we dynamically add variables? It can be added through globals()['new_var'], but please note that the global variables added here should be used with caution. The code is as follows:
As for how to add variables in the dynamic local scope, I really don’t know this, but you can work around it and define a dictionary variable and then assign it to it. The code is as follows:
By default, globals() can be operated directly with dict, but locals() is different. You can first think of locals() as a read-only dict (or a dict without write-back function) ), you can only know the local variables of your current code, but you cannot make it effective by modifying locals()
If you use exec to execute the code, specify a dict as the locals of this code, which can be modified