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

前端 未结 2 1927
刺人心
刺人心 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:25

    Just change the function definition to:

    def load():
        global var # this line has been added to the original code
        var = something()
    

    Global variables are read-only from sibling methods. More accurately unless a variable is specified as global, Python consider it as local, but a read access to a local variable name will reach module-level scope if the name is not present in local scope.

    See also use of “global” keyword in python and the doc for more details about the global statement

提交回复
热议问题