What does “global variables are bad” mean?

前端 未结 3 1473
野的像风
野的像风 2021-02-06 15:11

So I can read from a global variable

def f() :
  print x

And I can also assign it

def g()
  global x
  x = 3

3条回答
  •  再見小時候
    2021-02-06 15:37

    Global variables can be changed and access from nearly everywhere. This includes maybe colliding namespace and assignments,where you don't want to have them.

    To give an example:

    def someFunction(): 
        global myVar 
        myVar = "fuuu" 
        print myVar
    
    myVar = "baa" 
    f() 
    print myVar 
    

    Will end in something like.

    fuuu
    fuuu 
    

    Whereas you might expected

    fuuu 
    baa
    

    So I'd say both variants are little dangerous.

提交回复
热议问题