Defining lists as global variables in Python

前端 未结 3 718
日久生厌
日久生厌 2020-12-05 11:13

I am using a list on which some functions works in my program. This is a shared list actually and all of my functions can edit it. Is it really necessary to define it as \"g

3条回答
  •  温柔的废话
    2020-12-05 11:55

    When you assign a variable (x = ...), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:

    x = 0
    def f():
        x = 1
    f()
    print x #=>0
    

    and expect 1. Instead, you need do declare that you intend to use the global x:

    x = 0
    def f():
        global x
        x = 1
    f()
    print x #=>1
    

    But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.

    Also very important: Member assignment (x.name = ...), item assignment (collection[key] = ...), slice assignment (sliceable[start:end] = ...) and propably more are all method calls as well! And therefore you don't need global to change a global's members or call it methods (even when they mutate the object).

提交回复
热议问题