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

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

问题描述

#!/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.

推荐答案

这在

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.

通用样式是分配默认参数None,然后分配一个新列表.这可以解决整个歧义.

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天全站免登陆