函数 - python中的动态变量问题
怪我咯
怪我咯 2017-04-17 12:00:56
0
2
280

我是初学。在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没有被定义呢?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
大家讲道理

Look at a piece of code first

print locals
'''输出的是
{'__builtins__': <module '__builtin__' (built-in)>, '__name__':'__main__', '__doc__': None, '__package__': None}
'''
a = 1
print locals()
'''
输出是
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 1, '__package__': None}
注意:多了一个'a':1
'''
def b():
    print locals()
b()
'''
输出是
{}
'''
def b():
    c = 1
    print locals()
b()
'''
输出是
{'c':1}
'''

By now you should understand that locals actually means the current scope.
Then let’s execute a piece of code

print locals()
locals()['test'] = 1
print locals()
print test

The output is:

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'test': 1, '__doc__': None, '__package__': None}
1

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?

Next let’s talk about Python’s mechanism for finding variables.
When a line of code uses the value of variable x, Python will search for the variable in all available namespaces, in the following order:

  • Local namespace - refers specifically to the current function or method of the class. If the function defines a local variable x, Python will use this variable and stop searching.
  • Global namespace - specific to the current module. If the module defines a variable, function, or class named x, Python will use this variable and stop the search.
  • Built-in namespace - global to every module. As a last resort, Python will assume that x is a built-in function or variable.

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

def a():
    b = 1
    locals()['b'] = 2
    print b
a()  #输出为1

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:

def a():
    for i in range(3):
        globals()['part' + str(i)] = i
    print part0
    print part1
    print part2
a()
print part0
'''
输出为:
0
1
2
0
'''

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:

def a():
    b = {}
    for i in range(3):
        b['part' + str(i)] = i
    print b['part0']
    print b['part1']
    print b['part2']
a()
'''
输出为:
0
1
2
'''
黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!