gpt4 book ai didi

python - 更改全局范围对象

转载 作者:太空宇宙 更新时间:2023-11-04 09:12:44 27 4
gpt4 key购买 nike

我对 python 中的全局作用域有疑问。

我制作了这个脚本并且可以运行,但我不知道为什么:

#! /bin/python3
# -*- coding: UTF-8 -*-

data = []
stats = {'white':0, }

def main():
global data

with open(args.finput, 'r') as f:
data = f.readlines()

rwhitespaces()

with open(foutput, 'w') as f:
for line in data:
f.write(line)

print(stats)

def rwhitespaces():
cnt = 0
for line in data:
if line == '\n':
data.pop(cnt) # Modifing data var without global keywork and works, why??
stats['fistro'] = 1 # Modifing stats var without global keywork and works why??
cnt += 1

if __name__ == "__main__":
main()

所以我误解了一些全局范围的东西,有人可以解释一下吗???谢谢,抱歉我的英语不好

最佳答案

这是可行的,因为您没有更改引用,而是访问一个可变对象,并让它对自身执行更改。

global 需要将一个新值分配给全局范围的变量 (x = blah),但不需要仅仅访问一个变量。当您执行 data.pop(cnt) 时,您所做的只是访问变量,您可以在不使用 global 关键字的情况下执行此操作。

简而言之,这不是关于更改对象的属性,而是关于将对象分配给变量。

关于python - 更改全局范围对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13221042/

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