根据我的理解,Python有一个单独的函数名称空间,所以如果我想在函数中使用全局变量,我可能应该使用global。

然而,我能够访问一个全局变量,即使没有全局:

>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
...     return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'

为什么会这样?


另请参阅第一次使用后重新分配局部变量时发生的UnboundLocalError,以了解试图分配给全局变量而不使用全局变量时发生的错误。有关如何使用全局变量的一般问题,请参阅在函数中使用全局变量。


当前回答

Global使变量为Global

def out():
    global x
    x = 1
    print(x)
    return


out()

print (x)

这使得'x'就像函数外的普通变量一样。如果你把全局变量拿出来,它就会报错,因为它不能在函数中打印变量。

def out():
     # Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
    x = 1
    print(x)
    return


out()

print (x)

其他回答

Global使变量为Global

def out():
    global x
    x = 1
    print(x)
    return


out()

print (x)

这使得'x'就像函数外的普通变量一样。如果你把全局变量拿出来,它就会报错,因为它不能在函数中打印变量。

def out():
     # Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
    x = 1
    print(x)
    return


out()

print (x)

访问名称和分配名称是不同的。在本例中,您只是访问一个名称。

如果在函数中赋值给某个变量,则假定该变量为局部变量,除非将其声明为全局变量。如果没有,就假定它是全局的。

>>> x = 1         # global 
>>> def foo():
        print x       # accessing it, it is global

>>> foo()
1
>>> def foo():   
        x = 2        # local x
        print x 

>>> x            # global x
1
>>> foo()        # prints local x
2

虽然你可以在没有global关键字的情况下访问全局变量,但如果你想修改它们,你必须使用global关键字。例如:

foo = 1
def test():
    foo = 2 # new local foo

def blub():
    global foo
    foo = 3 # changes the value of the global foo

在这里,你只是访问了list sub。

这在Python常见问题解答中有很好的解释

What are the rules for local and global variables in Python? In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

在函数外部声明的任何变量都被假定为全局变量,只有在函数内部声明它们时(构造函数除外),你必须指定变量为全局变量。