Use of “global” keyword in Python

后端 未结 10 2424
既然无缘
既然无缘 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:47

    • You can access global keywords without keyword global
    • To be able to modify them you need to explicitly state that the keyword is global. Otherwise, the keyword will be declared in local scope.

    Example:

    words = [...] 
    
    def contains (word): 
        global words             # <- not really needed
        return (word in words) 
    
    def add (word): 
        global words             # must specify that we're working with a global keyword
        if word not in words: 
            words += [word]
    

提交回复
热议问题