python

时间:2017-12-30 14:07:31

标签: python scope

有些人可以向我解释一下这段代码

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:\Users\x126\Desktop\ss.py", line 12, in <module>
    main()
  File "C:\Users\x126\Desktop\ss.py", line 7, in main
    zap()
  File "C:\Users\x126\Desktop\ss.py", line 2, in zap
    print stype
NameError: global name 'stype' is not defined

2 个答案:

答案 0 :(得分:4)

这不是它的工作原理。 stypezap无法使用def zap(stype): print stype if True: # Of course this is unnecessary stype="something" zap(stype) ,因为它是在调用函数之前在其他位置定义的。您需要明确传递它:

{{1}}

或者你可以把它变成一个全球性的;虽然不推荐。总是倾向于将必要的数据作为参数而不是全局,因为滥用全局变量往往会使程序长期复杂化。

答案 1 :(得分:0)

使用全局变量:

stype ="ori"

def zap():
    print (stype)

def main():
    global stype
    if True:
        stype="something"
        zap()    
    else:
        stype="something else"

if __name__ == '__main__':
    main()

输出:

something