Why can't I set a global variable in Python?

后端 未结 4 1475

How do global variables work in Python? I know global variables are evil, I\'m just experimenting.

This does not work in python:

G = None

def foo()         


        
相关标签:
4条回答
  • 2020-12-02 15:02

    You need the global statement:

    def foo():
        global G
        if G is None:
            G = 1
    

    In Python, variables that you assign to become local variables by default. You need to use global to declare them as global variables. On the other hand, variables that you refer to but do not assign to do not automatically become local variables. These variables refer to the closest variable in an enclosing scope.

    Python 3.x introduces the nonlocal statement which is analogous to global, but binds the variable to its nearest enclosing scope. For example:

    def foo():
        x = 5
        def bar():
            nonlocal x
            x = x * 2
        bar()
        return x
    

    This function returns 10 when called.

    0 讨论(0)
  • 2020-12-02 15:09

    You still have to declare G as global, from within that function:

    G = None
    
    def foo():
        global G
        if G is None:
            G = 1
    
    foo()
    print G
    

    which simply outputs

    1
    
    0 讨论(0)
  • 2020-12-02 15:09

    You need to declare G as global, but as for why: whenever you refer to a variable inside a function, if you set the variable anywhere in that function, Python assumes that it's a local variable. So if a local variable by that name doesn't exist at that point in the code, you'll get the UnboundLocalError. If you actually meant to refer to a global variable, as in your question, you need the global keyword to tell Python that's what you meant.

    If you don't assign to the variable anywhere in the function, but only access its value, Python will use the global variable by that name if one exists. So you could do:

    G = None
    
    def foo():
        if G is None:
            print G
    
    foo()
    

    This code prints None and does not throw the UnboundLocalError.

    0 讨论(0)
  • 2020-12-02 15:15

    Define G as global in the function like this:

    #!/usr/bin/python
    
    G = None;
    def foo():
        global G
        if G is None:
            G = 1;
        print G;
    
    foo();
    

    The above python prints 1.

    Using global variables like this is bad practice because: http://c2.com/cgi/wiki?GlobalVariablesAreBad

    0 讨论(0)
提交回复
热议问题