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
WizardYu
V2EX  ›  Python

Python 萌新请教有关 global 变量和 OrderedDict 的问题

  •  1
     
  •   WizardYu · 2019-08-31 07:18:47 +08:00 · 1464 次点击
    这是一个创建于 1715 天前的主题,其中的信息可能已经有所发展或是发生改变。
    from collections import OrderedDict

    dict = OrderedDict()
    def main():
    list = [['a', 1], ['b', 2], ['c', 3]]
    global dict = OrderedDict(list)

    最后一句报语法错误,请大佬指点一下原因...
    5 条回复    2019-08-31 08:15:54 +08:00
    banxi1988
        1
    banxi1988  
       2019-08-31 07:53:47 +08:00
    1. 错误提示很明显. `dict` 重定义了.
    你可以看 `global` 关键词的说明:
    > Names listed in a global statement must not be used in the same code block textually preceding that global statement.

    2. dict 是内置的类名,用来作变量名,习惯不好.

    3. 发贴不注意缩进, 差评.
    echo1937
        2
    echo1937  
       2019-08-31 07:57:08 +08:00   ❤️ 1
    首先,使用 global 时,先声明,再赋值:
    global dict
    dict = OrderedDict(list)

    其次,dict 是 build-in name,最好不要拿来当变量名
    WizardYu
        3
    WizardYu  
    OP
       2019-08-31 07:58:19 +08:00 via Android
    @banxi1988 emmm 我暂时还不知道怎么在这里缩进😂不好意思我会查一查
    WizardYu
        4
    WizardYu  
    OP
       2019-08-31 08:13:15 +08:00 via Android
    @echo1937 @banxi1988 解决啦!谢谢你们 hhh,是没有提前声明的事,命名问题我以后也会注意
    swulling
        5
    swulling  
       2019-08-31 08:15:54 +08:00 via iPhone
    原则上别用全局变量
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   928 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:45 · PVG 05:45 · LAX 14:45 · JFK 17:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.