python 函数内部修改全局变量

本文介绍如何正确地在Python函数中使用全局变量,包括不同情况下对全局变量进行修改的方法,并展示了如何避免重复读取的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有一个全局file_content 的list,在函数内部向其append数据,是可以的,不需要加global 修饰,
但是当 在函数内部进行对其 赋值操作时,需要用global修饰该全局变量,因为赋值操作默认作为局部变量,
对全局变量进行赋值修改,需要进行显示global声明
每一次读取file_content时候,读取完或者开始读取的时候要重新对该list清空,
防止每次读取都会将上一次内容读重复读取到,所以在赋值为空的时候 就必须用到global修饰该list变量,
python2.7 赋值为空有两种方法:1、file_content=[] 赋个空list
2、del file_content=[:] 删除元素
python3中list有clear()方法更加方便

file_content = list()

def  add_file(code):
    global file_content
    del file_content[:] # file_content = []
    for i in range(10):
        file_content.append(str(code)+"-helloworld-"+str(i))


def read_file():
    # global file_content
    for line in file_content:
        print(line)
    # file_content = []
    # file_content.clear()


if __name__ == '__main__':

    for i in range(3):
        add_file(i)
        read_file()
0-helloworld-0
0-helloworld-1
0-helloworld-2
0-helloworld-3
0-helloworld-4
0-helloworld-5
0-helloworld-6
0-helloworld-7
0-helloworld-8
0-helloworld-9
1-helloworld-0
1-helloworld-1
1-helloworld-2
1-helloworld-3
1-helloworld-4
1-helloworld-5
1-helloworld-6
1-helloworld-7
1-helloworld-8
1-helloworld-9
2-helloworld-0
2-helloworld-1
2-helloworld-2
2-helloworld-3
2-helloworld-4
2-helloworld-5
2-helloworld-6
2-helloworld-7
2-helloworld-8
2-helloworld-9
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值