使用openpyexcel制作密码生成器时遇到的问题

29 浏览
0 Comments

使用openpyexcel制作密码生成器时遇到的问题

这个问题已经有答案了

如何通过引用传递变量?

为什么函数可以改变某些参数,但却无法改变其他参数?

这可能看起来是一个非常愚蠢的问题,但我对Python中的作用域规则感到困惑。在下面的示例中,我向一个函数发送了两个带有值的变量(x,y),该函数应该更改它们的值。当我打印结果时,变量没有改变。

def func1(x,y):
    x=200
    y=300
x=2
y=3
func1(x,y)
print x,y #prints 2,3

现在,如果这是C ++,我会通过引用(&)将它们发送到该函数中,因此可以更改它们的值。那么在Python中的等效物是什么?更重要的是,当您将对象发送到函数时会发生什么? Python会创建这些对象的新引用吗?

admin 更改状态以发布 2023年5月21日
0
0 Comments

把它们看作是函数的一部分。当函数结束时,所有的变量也随之消失。

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

为什么这行不通呢?因为您从未告诉程序对那个元组 (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

0