变异、重新绑定、复制值和赋值运算符之间的区别 [英] Difference between mutation, rebinding, copying value, and assignment operator

查看:18
本文介绍了变异、重新绑定、复制值和赋值运算符之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/env python3.2

def f1(a, l=[]):
    l.append(a)
    return(l)

print(f1(1))
print(f1(1))
print(f1(1))

def f2(a, b=1):
    b = b + 1
    return(a+b)

print(f2(1))
print(f2(1))
print(f2(1))

f1中,参数l有一个默认值赋值,并且只求值一次,所以三个print输出1, 2, 和 3. 为什么 f2 不做类似的事情?

In f1 the argument l has a default value assignment, and it is only evaluated once, so the three print output 1, 2, and 3. Why f2 doesn't do the similar?

为了使我所学的内容更易于浏览此线程的未来读者,我总结如下:

To make what I learned easier to navigate for future readers of this thread, I summarize as the following:

  • 我发现了这个很好的教程话题.

我制作了一些简单的示例程序比较变异重新绑定复制值赋值运算符之间的区别.

I made some simple example programs to compare the difference between mutation, rebinding, copying value, and assignment operator.

推荐答案

这在 相对流行的 SO 问题,但我会尝试在您的特定上下文中解释该问题.

This is covered in detail in a relatively popular SO question, but I'll try to explain the issue in your particular context.

当你声明你的函数时,默认参数会在那一刻被评估.每次调用函数时都不会刷新.

When your declare your function, the default parameters get evaluated at that moment. It does not refresh every time you call the function.

你的函数行为不同的原因是你对待它们的方式不同.在 f1 中,您正在改变对象,而在 f2 中,您正在创建一个新的整数对象并将其分配给 b.您不是在此处修改 b,而是在重新分配它.现在它是一个不同的对象.在 f1 中,您保留相同的对象.

The reason why your functions behave differently is because you are treating them differently. In f1 you are mutating the object, while in f2 you are creating a new integer object and assigning it into b. You are not modifying b here, you are reassigning it. It is a different object now. In f1, you keep the same object around.

考虑替代函数:

def f3(a, l= []):
   l = l + [a]
   return l

这类似于 f2 并且不会一直附加到默认列表中.这是因为它正在创建一个新的 l 而不修改默认参数中的对象.

This behaves like f2 and doesn't keep appending to the default list. This is because it is creating a new l without ever modifying the object in the default parameter.

python中常见的做法是赋值None的默认参数,然后赋值一个新的list.这解决了整个歧义.

Common style in python is to assign the default parameter of None, then assign a new list. This gets around this whole ambiguity.

def f1(a, l = None):
   if l is None:
       l = []

   l.append(a)

   return l

这篇关于变异、重新绑定、复制值和赋值运算符之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆