Python function global variables?

前端 未结 6 726
广开言路
广开言路 2020-11-22 04:49

I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (

6条回答
  •  囚心锁ツ
    2020-11-22 05:12

    As others have noted, you need to declare a variable global in a function when you want that function to be able to modify the global variable. If you only want to access it, then you don't need global.

    To go into a bit more detail on that, what "modify" means is this: if you want to re-bind the global name so it points to a different object, the name must be declared global in the function.

    Many operations that modify (mutate) an object do not re-bind the global name to point to a different object, and so they are all valid without declaring the name global in the function.

    d = {}
    l = []
    o = type("object", (object,), {})()
    
    def valid():     # these are all valid without declaring any names global!
       d[0] = 1      # changes what's in d, but d still points to the same object
       d[0] += 1     # ditto
       d.clear()     # ditto! d is now empty but it`s still the same object!
       l.append(0)   # l is still the same list but has an additional member
       o.test = 1    # creating new attribute on o, but o is still the same object
    

提交回复
热议问题