Accessing module level variables, from within a function in the module

前端 未结 2 1972
刺人心
刺人心 2021-01-31 14:25

I\'d like to be able to do something like this:

#mymodule
var = None

def load():
    var = something()

Other module(s):

#secon         


        
2条回答
  •  忘了有多久
    2021-01-31 14:34

    You seem to mostly have it. You are missing only the fact that "module-level" variables are called global in Python. (They are not truly global, but only global to the module they are declared in, in other words.)

    In any function where you modify a global variable (you want to make the name refer to a different object), it must be declared global. So your load() function needs a global var at the beginning. If you are only using the value of a global variable, or if it is a mutable type such as a list and you are modifying it, but not changing the object that the name points to, you needn't declare it global.

    The import statement is, as you have discovered, how you can import a module-level variable from one module into another.

提交回复
热议问题