python如何限制变量取值范围_如何更改函数中变量的范围?Python

把它们看作是功能的一部分。当函数结束时,它的所有变量也会消失。x=2

y=3

def func(x,y):

x=200

y=300

func(x,y) #inside this function, x=200 and y=300

#but by this line the function is over and those new values are discarded

print(x,y) #so this is looking at the outer scope again

如果你想让一个函数按照你写的方式修改一个值,你可以使用一个global但是这是非常糟糕的做法。def func(x,y):

global x #these tell the function to look at the outer scope

global y #and use those references to x and y, not the inner scope

x=200

y=300

func(x,y)

print(x,y) #prints 200 300

问题在于,在最好的情况下,它会使调试成为一场噩梦,而在最坏的情况下,调试则是完全不可能的。像这样的事情在函数中通常被称为“副作用”——设置一个不需要设置的值,并且在不显式返回它的情况下这样做是一件坏事。通常,您应该编写的惟一修改项目的函数是对象方法(比如[].append()修改列表,因为返回一个新列表是愚蠢的!)

这样做的正确方法是使用返回值。试试像这样的def func(x,y):

x = x+200 #this can be written x += 200

y = y+300 #as above: y += 300

return (x,y) #returns a tuple (x,y)

x = 2

y = 3

func(x,y) # returns (202, 303)

print(x,y) #prints 2 3

为什么不起作用?好吧,因为你从未告诉程序对那个元组做任何事情,只是为了计算它。现在就分配吧#func as defined above

x=2 ; y=3

x,y = func(x,y) #this unpacks the tuple (202,303) into two values and x and y

print(x,y) #prints 202 303

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值