python定义全局列表_Python:修改函数内的全局列表

First of all, I understand that I can use global statement to access global variables. But somehow I was able to modify a global list without global like below:

def func1(nums):

nums = [4,5,6]

nums = [1,2,3]

func1(nums)

print nums # print [1,2,3]

def func2(nums):

nums[0] = 4

nums[1] = 5

nums[2] = 6

nums = [1,2,3]

func2(nums)

print nums # print [4,5,6]

After trying func2, I realized that I can always access global list in a function if I specify the index:

def func3(nums):

nums[:] = [4,5,6]

nums = [1,2,3]

func3(nums)

print nums # print [4,5,6]

Is it because Python automatically go trying to match a global variable if a function variable is used before definition?

Thanks.

解决方案I understand that I can use global statement to access global variables

Your understanding is wrong. You can always access a global variable as long as you don't have a local variable of the same name. You only need the global statement when you are going to change what object a variable name refers to. In your func2, you are not doing that; you are only changing the contents of the object. nums still refers to the same list.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值