smdbh
V2EX  ›  Python

变量作用域问题, shadow name x from outer scope

By smdbh at 2018 年 7 月 4 日 · 5869 次点击
一个字符串拼接函数
def func(ver):
__ret = ''
__for k, v in ver.items():
____ret += '{0}:{1}'.format(k, v)
__return ret

问题是第二行的 ret='' 回报 shadow name ret from outer scope 的错误。要再 for 循环里加 global ret 才能去掉。
我想问下,这类代码,常规做法是怎么做的?
第 1 条附言  ·  2018 年 7 月 4 日
在 __main__ 中的变量和函数里的一致,会造成这个警告。命名要不一样。
3 条回复  •  2018-07-04 11:01:30 +08:00
whoami9894
   1
whoami9894  
   2018 年 7 月 4 日 via Android
你在函数外部定义了同名变量
scmod
   2
scmod  
   2018 年 7 月 4 日
这个是错误吗~?我感觉这种是警告是不是会比较好..
simple2025
   3
simple2025  
   2018 年 7 月 4 日
这个不是 pycharm 的警告吗?
推荐学习书目
› 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
© 2026 V2EX · 37ms · 3.9.8.5