Python函数使用全局变量

时间:2018-02-23 01:26:55

标签: python python-3.x function global-variables

为什么python有以下行为?

a = 4
def f1(): # No error: Returns 5. Global a unchanged
    a = 5
    return a
def f2(): # No error. Returns value of global a
    return a
def f3(): # Error: a used before assignment
    a = a + 1
    return a
def f4(): # Error: a used before assignment
    b = a
    a = b + 1
    return a
def f5(): # No error. Returns value of global a
    b = a
    return b

似乎Python有时允许使用全局变量a,有时候不会。什么规则指导这个?

0 个答案:

没有答案