When do I need to use the global keyword in python

前端 未结 4 381
攒了一身酷
攒了一身酷 2021-01-03 03:30

Okay, so I\'ve had this really annoying problem where a variable got set locally but then outside of that function reverted to it\'s old self (in this case None), but at the

相关标签:
4条回答
  • 2021-01-03 03:44

    When you do things to foo and foo_foo, you're not changing the reference:

    foo = {}
    foo['key'] = 'stuff'
    

    foo still refers to the same object as before; it just now contains more data.

    bar = ['key', 'value']
    

    This reassigns bar to refer to a new object (the list with two elements).

    However, when that line is encountered inside a function, it creates a local reference bar unless you say global bar. In effect, you have two different variables named bar: the global and the local.

    Saying global bar tells Python to use the global version of bar rather than creating a new local variable with the same name.

    Generally, if you are modifying global variables, you should state global varname for each one to avoid accidentally creating a local.

    Or, you can use a class:

    class State(object):
        def __init__(self):
            self.foo = {}
            self.foo_foo = {}
            self.bar = None
    
    state = State()
    
    def fn():
        state.bar = ['key', 'value']
    
    0 讨论(0)
  • 2021-01-03 03:50

    If you only need to read the value of a global variable in a function, you don't need the global keyword:

    x = 3
    def f():
        print x
    

    If you ever set the value of a global variable, you need the keyword so that you don't create a local variable:

    x = 3
    def f():
        global x
        x = 5
    
    f()
    print x
    
    0 讨论(0)
  • 2021-01-03 03:52

    Variables you define in function are accessible only from this function's body.

    0 讨论(0)
  • 2021-01-03 04:09

    You can read variables from the global scope from within a function, but you can't modify their values without using the "global" keyword.

    When you attempt to set bar =[key, value], a new bar variable is added to your function's namespace. From then on, bar references this new variable, and not the global one.

    Although you can read the global bar's value, once you attempt to re-assign it a value from within your function, you've actually created a new bar and are not acting on the global one.

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