这看起来似乎是一件相当奇怪的事情,但我很好奇是否可以在 Python 中的调用链中隐式传递变量而不将其作为参数传递。为了更好地说明这里有一个例子:
这是“正常”方式:
def three(something):
print(something)
def two(something):
# ...
three(something)
def one(something):
# ...
two(something)
这就是我想要做的事情:
def three():
# something is defined implicitly
print(something)
def two():
# ...
three()
def one(something):
# somehow define something inside a context
# for this activation
two()
为此,one
、two
和 third
不在同一个类中,甚至不在同一个模块中。
最佳答案
您不想这样做。
如果您确实想折磨自己,那么您可以创建一个单独的线程并在该线程中运行对
one()
的调用。然后只需使用threading.local
作为共享状态即可。你真的不想这样做。
以下是如何使用线程本地存储:
import threading
state = threading.local()
def three():
# something is defined implicitly
print(state.something)
def two():
# ...
three()
def one(something):
# somehow define something inside a context
# for this activation
def inner():
state.something = something
two()
t = threading.Thread(target=inner)
t.start()
t.join()
if __name__=='__main__':
one(42)
one(24)
关于python - Python 中的每次激活 "global"变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032824/