Global variable with imports

后端 未结 3 1295
不知归路
不知归路 2020-12-08 10:13

first.py

myGlobal = \"hello\"

def changeGlobal():
   myGlobal=\"bye\"

second.py

from first import *

changeGlobal()
pr         


        
3条回答
  •  借酒劲吻你
    2020-12-08 10:45

    Try:

    def changeGlobal():
        global myGlobal
        myGlobal = "bye"
    

    Actually, that doesn't work either. When you import *, you create a new local module global myGlobal that is immune to the change you intend (as long as you're not mutating the variable, see below). You can use this instead:

    import nice
    
    nice.changeGlobal()
    print nice.myGlobal
    

    Or:

    myGlobal = "hello"
    
    def changeGlobal():
       global myGlobal
       myGlobal="bye"
    
    changeGlobal()
    

    However, if your global is a mutable container, you're now holding a reference to a mutable and are able to see changes done to it:

    myGlobal = ["hello"]
    
    def changeGlobal():
        myGlobal[0] = "bye"
    

提交回复
热议问题