gpt4 book ai didi

python - 从多个 Python 文件更改相同的文件范围变量

转载 作者:行者123 更新时间:2023-12-05 07:49:52 24 4
gpt4 key购买 nike

看来,如果我通过 import 语句从多个文件导入同一个 Python 文件并更改其中的一些文件范围变量,则在容器更改时,其他模块将看不到引用更改会的。

例如,

第一个例子

第一个.py

import reader
import helper


reader.change_buf('modified')
helper.foo()

second.py

import reader


def foo():
print(reader.BUF)

reader.py

buf = 'original'


def change_buf(buf):
buf = buf

输出

> python first.py
original

第二个例子

第一个.py

import reader
import helper


reader.change_first_element('1')
helper.foo()

second.py

import reader


def foo():
print(reader.BUF)

reader.py

buf = ['0', '1', '2']


def change_first_element(new_elem):
buf[0] = new_elem

输出

> python first.py
['1', '1', '2']

为什么?

最佳答案

因为在第一个例子中你隐藏了全局变量 buf 在一个局部变量(函数参数 buf)后面,而在第二个例子中函数参数(new_elem) 不会发生碰撞。但这还不是全部。在第一个示例中,您在函数中定义变量 buf,因此默认情况下它仍然是本地的 - 在第二个示例中,您使用它是因为您设置了 buf[0]。您必须将其声明为 global

你应该这样写reader.py:

buf = 'original'

def change_buf(new_val):
global buf
buf = new_val

关于python - 从多个 Python 文件更改相同的文件范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36842224/

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