Global variable with imports

后端 未结 3 1297
不知归路
不知归路 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:35

    I had once the same concern as yours and reading the following section from Norman Matloff's Quick and Painless Python Tutorial was really a good help. Here is what you need to understand (copied from Matloff's book):

    Python does not truly allow global variables in the sense that C/C++ do. An imported Python module will not have direct access to the globals in the module which imports it, nor vice versa.

    For instance, consider these two files, x.py,

    # x.py
    import y
    def f():
      global x
      x = 6
    def main():
      global x
      x = 3
    f()
    y.g()
    if __name__ == ’__main__’:
      main()
    

    and y.py:

    # y.py
    def g():
      global x
      x += 1
    

    The variable x in x.py is visible throughout the module x.py, but not in y.py. In fact, execution of the line x += 1

    in the latter will cause an error message to appear, “global name ’x’ is not defined.”

    Indeed, a global variable in a module is merely an attribute (i.e. a member entity) of that module, similar to a class variable’s role within a class. When module B is imported by module A, B’s namespace is copied to A’s. If module B has a global variable X, then module A will create a variable of that name, whose initial value is whatever module B had for its variable of that name at the time of importing. But changes to X in one of the modules will NOT be reflected in the other.

    Say X does change in B, but we want code in A to be able to get the latest value of X in B. We can do that by including a function, say named GetX() in B. Assuming that A imported everything from B, then A will get a function GetX() which is a copy of B’s function of that name, and whose sole purpose is to return the value of X. Unless B changes that function (which is possible, e.g. functions may be assigned), the functions in the two modules will always be the same, and thus A can use its function to get the value of X in B.

提交回复
热议问题