python中变量的范围[重复]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中变量的范围[重复]相关的知识,希望对你有一定的参考价值。
这个问题在这里已有答案:
有些人可以向我解释一下这段代码
def zap():
print stype
def main():
if True:
stype="something"
zap()
else:
stype="something else"
if __name__ == '__main__':
main()
在调用zap函数之前已经定义了stype
但是我收到了这个错误。
Traceback (most recent call last):
File "C:Usersx126Desktopss.py", line 12, in <module>
main()
File "C:Usersx126Desktopss.py", line 7, in main
zap()
File "C:Usersx126Desktopss.py", line 2, in zap
print stype
NameError: global name 'stype' is not defined
答案
这不是它的工作原理。 stype
在zap
中不可用只是因为它在您调用函数之前已在其他地方定义。您需要明确传递它:
def zap(stype):
print stype
if True: # Of course this is unnecessary
stype="something"
zap(stype)
或者你可以把它变成一个全球性的;虽然不建议这样做。总是倾向于将必要的数据作为参数而不是全局,因为滥用全局变量往往会使程序长期复杂化。
另一答案
要使用全局变量:
stype ="ori"
def zap():
print (stype)
def main():
global stype
if True:
stype="something"
zap()
else:
stype="something else"
if __name__ == '__main__':
main()
输出:
something
以上是关于python中变量的范围[重复]的主要内容,如果未能解决你的问题,请参考以下文章