accessing “module scope” vars

前端 未结 4 1449
醉酒成梦
醉酒成梦 2020-12-14 03:02

I\'m currently learning Python, and I have to work on a Python 2.7 project.

Accessing \"module scope\" variables in functions of the module itself is a bit confusing

4条回答
  •  不知归路
    2020-12-14 03:15

    You probably want to read up on Python's namespaces. Way 1 is correct but generally unnecessary, never use 2. An easier approach is to just use a dict (or class or some other object):

    my_globals = {'var': None}
    
    def my_func():
        my_globals['var'] = 'something else'
    

    Assignments always go into the innermost scope and the innermost scope is always searched first, thus the need for the global keyword. In this case you aren't assigning to a name, so it's unnecessary.

提交回复
热议问题