如何更改函数中变量的范围?蟒蛇

Reb*_*_87 1 python scope function

这似乎是一个非常愚蠢的问题,但是我对Python的范围规则感到困惑。在下面的示例中,我将带有值的两个变量(x,y)发送到应该更改其值的函数。当我打印结果时,变量没有改变。

def func1(x,y):
    x=200
    y=300

x=2
y=3

func1(x,y)

print x,y #prints 2,3
Run Code Online (Sandbox Code Playgroud)

现在,如果这是C ++,我将通过引用(&)将其发送给该函数,从而可以更改其值。那么,Python中的等价物是什么?更重要的是,将对象发送给函数时实际发生了什么?Python是否对这些对象进行了新引用?

Ada*_*ith 5

将它们视为功能的一部分。函数结束时,其所有变量也将消失。

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
Run Code Online (Sandbox Code Playgroud)

如果您希望函数以与编写时完全相同的方式修改值,则可以使用a,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
Run Code Online (Sandbox Code Playgroud)

问题在于,这在最佳情况下会使调试成为噩梦,而在最坏情况下则完全不可能进行调试。诸如此类的事情在函数中通常被称为“副作用”-设置不需要设置的值,并且在没有显式返回它的情况下这样做是一件坏事。通常,您应该编写的用于就地修改项目的唯一函数是对象方法(诸如[].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
Run Code Online (Sandbox Code Playgroud)

为什么没有用?好吧,因为您从未告诉程序使用该元组执行任何操作(202, 303),只是为了计算它。现在分配它

#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
Run Code Online (Sandbox Code Playgroud)