gpt4 book ai didi

Python全局变量疯狂

转载 作者:太空狗 更新时间:2023-10-29 17:28:29 25 4
gpt4 key购买 nike

你有三个文件:main.py、second.py 和 common.py

通用.py

#!/usr/bin/python
GLOBAL_ONE = "Frank"

主要.py

#!/usr/bin/python
from common import *
from second import secondTest

if __name__ == "__main__":
global GLOBAL_ONE
print GLOBAL_ONE #Prints "Frank"
GLOBAL_ONE = "Bob"
print GLOBAL_ONE #Prints "Bob"

secondTest()

print GLOBAL_ONE #Prints "Bob"

第二个.py

#!/usr/bin/python
from common import *

def secondTest():
global GLOBAL_ONE
print GLOBAL_ONE #Prints "Frank"

为什么 secondTest 不使用其调用程序的全局变量?如果事实上它不是,那么称其为“全局”有什么意义!?

为了让 secondTest(或我从 main 调用的任何外部函数)识别和使用正确的变量,我错过了什么?

最佳答案

global 意味着这个模块是全局的,而不是整个程序。当你做的时候

from lala import *

您将lala 的所有定义作为locals 添加到此模块

因此,在您的情况下,您会得到两份 GLOBAL_ONE

关于Python全局变量疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3119287/

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