推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
noobsheldon
V2EX  ›  Python

exec 语句对 locals() 结果的影响有点不解, 请教一下!

  •  
  •   noobsheldon · Oct 2, 2017 · 2004 views
    This topic created in 3170 days ago, the information mentioned may be changed or developed.
    x = 30
    def out():
        x = 50
        def inner():
            print x
            print locals()
        return inner
    out()()    # 此处 print locals()  结果 {'x': 50}
    

    ============另一个 Python shell 中

    x =30
    def out():
        x = 50
        def inner():
            print x
            print locals()
            exec 'print x' in globals(), locals()
        return inner
    out()()    # 此处 print locals()  结果 {}
    
    2 replies    2017-10-10 18:14:13 +08:00
    babywhisper
        1
    babywhisper  
       Oct 10, 2017
    exec 'print x' in locals(), globals()

    这句话的意思是:
    把 locals()返回的字典, 当做'print x'的全局域(global scope)
    把 globals()返回的字典, 作为要执行的'print x'的 local scope

    所以 exec 'print x' in globals(), locals() 就相当于 print globals()['x']
    打印出的是 30

    那么问题来了, 为什么`print locals()`是个空字典呢?
    感觉是因为编译的时候?? local scope 被拿去占用了, 原来的被新生成的替代了.
    执行完 exec 'print x' in globals(), locals()后, x 也消失了.


    不知道楼主有没有什么新发现??
    noobsheldon
        2
    noobsheldon  
    OP
       Oct 10, 2017
    @daya0576
    x = 30
    exec_local = {'x': 100}
    def out():
    x = 50
    def inner():
    print x
    print locals()
    exec 'print x' in globals(), exec_local
    print exec_local
    print x
    return inner

    out()() #===>

    50
    {}
    100
    {'x': 100}
    50
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2806 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:15 · PVG 20:15 · LAX 05:15 · JFK 08:15
    ♥ Do have faith in what you're doing.