gpt4 book ai didi

python - 将全局变量传递给 Python 中的另一个文件?

转载 作者:行者123 更新时间:2023-11-28 20:23:29 26 4
gpt4 key购买 nike

我有

# file1.py
global a, b, c, d, e, f, g

def useful1():
# a lot of things that uses a, b, c, d, e, f, g

def useful2():
useful1()
# a lot of things that uses a, b, c, d, e, f, g

def bonjour():
# a lot of things that uses a, b, c, d, e, f, g
useful2()

# main.py   (main file)
import file1

# here I would like to set the value of a, b, c, d, e, f, g of file1 !

bonjour()

如何处理所有这些全局变量?

PS:我不想为所有函数添加 a, b, c, d, e, f, g,这样做会很多余:

def useful1(a, b, c, d, e, f, g):
...
def useful2(a, b, c, d, e, f, g):
...
def bonjour(a, b, c, d, e, f, g):
...

最佳答案

您不需要通过它们。如果您已经在 main.py 的顶部完成了 import file1,您可以直接引用 file1.a 等。

但是,有这么多全局变量闻起来很糟糕。您可能应该使用类进行重构。

关于python - 将全局变量传递给 Python 中的另一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20419827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com