在 Python 中通过全局关键字从外部作用域访问变量

Accessing a variable from outer scope via global keyword in Python

根据这个 Question's accepted answer,我知道我不能创建纯全局变量。不错不错

然而,他接着说:

[..]all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.[..]

好的,所以我们不能在原始意义上分配全局变量,但似乎可以通过 global 关键字从包内访问最外层范围内的变量,对吗?

然后,显然,在我努力访问通过命令行参数传递给我的 python 程序的变量时,我遗漏了一些重要的东西。

我的程序有通常的 __main__.py,它处理参数解析并执行来自我的 python 模块 backend 的代码。

backend 具有依赖于通过命令行参数输入的代码。但是,我似乎无法将这些参数提供给 backend

我的包裹布局是:

mypackage
- __main__.py
- backend/
    -__init__.py
    -direction.py

这是__main__.py

import argparse

# Setup ArgParser
parser = argparse.ArgumentParser(description="Fancy Description of program.")
parser.add_argument('--tar', nargs=1, dest='target',
                help='Specify output folder.',
                default=['/path/to/output'])

target_dir = args.target[0]

# Import backend now that our variable is set.
from backend.direction import direction

还有我的backend/direction.py

global target_dir
print(target_dir)

运行 这引发了 NameError: 'target_dir' is not defined。 那么大便在哪里? 我是在假设这是不可能的,还是我只是搞砸了声明?

global 仅在使用它的模块内工作。您也不要使用 global 声明 全局范围内的全局变量(即模块范围)。您可以在函数范围内使用 global 来指示您要在全局范围内而不是在局部范围内使用变量。

在 python 3 中,还有一个 nonlocal 关键字,它允许您指示要修改外部范围 中的变量,而不是 global/module范围.

全球

A = 1

def global_func():
    global A
    A = 2


def func():
    A = 3


print(A)
# 1

global_func()
print(A)
# 2

func()
print(A)
# 2

非本地

def outside():
    a = 1

    def inside_nonlocal():
        nonlocal a
        a = 2

    def inside():
        a = 3

    print(a)
    # 1

    inside_nonlocal()
    print(a)
    # 2

    inside()
    print(a)
    # 2

我不清楚你的问题到底是什么。是不是不能做下面的事情?

import backend

if __name__ == "__main__":
    # parse arguments
    backend.argreceive(arguments)

正如 Daniel Roseman 所建议的,如果有许多后端函数需要访问这些变量,那么您应该考虑使用 class 和 class 属性来存储变量。

class argreceive():
    def __init__(self,args):
        self.args = args