简体   繁体   中英

What's the difference between locals() and globals()

I don't understand what's wrong with in this code.

Please let me know how I write to solve this problem.

I'd thought that this might had been good, but it caused the error.

>>> def L():
...     for i in range(3):
...             locals()["str" + str(i)] = 1
...     print str0
... 
>>> L()

If I execute it, the following error happened.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in a
NameError: global name 'str0' is not defined

However, if I use globals() , the error didn't happen(like the following)

>>> def G():
...     for i in range(3):
...             globals()["str" + str(i)] = 1
...     print str0
... 
>>> G()
1

But!!! If I don't use for statement, I can write like this and works well.

>>> def LL():
...     locals()["str" + str(0)] = 1
...     print str0
... 
>>> LL()
1

I want to get the result by using variables set in the method after the above code was executed.

>>> str0
1
>>> str1
1
>>> str2
1

From the documentation of locals()

Note:

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM