Use of “global” keyword in Python

后端 未结 10 2676
既然无缘
既然无缘 2020-11-21 05:05

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to us

10条回答
  •  庸人自扰
    2020-11-21 05:46

    The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

    def bob():
        me = "locally defined"    # Defined only in local context
        print(me)
    
    bob()
    print(me)     # Asking for a global variable
    

    The above will give you:

    locally defined
    Traceback (most recent call last):
      File "file.py", line 9, in 
        print(me)
    NameError: name 'me' is not defined
    

    While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.

    def bob():
        global me
        me = "locally defined"   # Defined locally but declared as global
        print(me)
    
    bob()
    print(me)     # Asking for a global variable
    

    So the above code will give you:

    locally defined
    locally defined
    

    In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.

提交回复
热议问题