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

有个 python 报错,请懂的解释一下该如何理解?

  •  
  •   hao1032 · 2016-07-22 14:16:22 +08:00 · 2365 次点击
    这是一个创建于 2836 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import time

    def foo():
    print time.time()
    time = 1

    foo()

    执行后报错:
    print time.time()
    UnboundLocalError: local variable 'time' referenced before assignment

    疑问,如果 foo 里面任何一句单独存在都不会报错。但是一起存在就出错。 python 的动态特性在这个情况下为什么不行了呢?
    3 条回复    2016-07-22 14:23:26 +08:00
    besttime
        1
    besttime  
       2016-07-22 14:20:54 +08:00
    肯定不可以啊 ,你模块名是 time 。一个变量名也是 time ,你的 time , Python 解释器是把它当成变量处理,还是模块处理呢?
    2225377fjs
        2
    2225377fjs  
       2016-07-22 14:21:55 +08:00
    这是 Python 语言机制的特性,因为你在 foo 函数作用域里面有一个
    time = 1
    这里就理解成为了申明创建一个 time 变量,而且赋值为 1 ,会自动断开外部作用域里面 import 的 time 的关联。。
    所以最外部的 time 变量就跟当前函数没有任何关系了。。。
    而这个时候 time 的创建赋值之前又调用了 time.time(),所以就报错了。。。

    总之: python 语言作用域的机制特性造成的问题。
    2225377fjs
        3
    2225377fjs  
       2016-07-22 14:23:26 +08:00
    你在 time.time() 之前加上一个 global time 语句就可以了,就强制关联函了外部 import 的 time 了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1484 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 16:57 · PVG 00:57 · LAX 09:57 · JFK 12:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.