V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2017-10-02 15:55:02 +08:00 · 1490 次点击
    这是一个创建于 2397 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2017-10-10 18:14:13 +08:00
    daya0576
        1
    daya0576  
       2017-10-10 17:35:55 +08:00
    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
       2017-10-10 18:14:13 +08:00
    @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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5215 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:28 · PVG 17:28 · LAX 02:28 · JFK 05:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.