+= 在 python 中到底做了什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4841436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:47:04  来源:igfitidea点击:

What exactly does += do in python?

pythonoperatorsnotationshorthandcompound-assignment

提问by Salvatore Mucciolo

I need to know what += does in python. It's that simple. I also would appreciate links to definitions of other short hand tools in python.

我需要知道 += 在 python 中的作用。就这么简单。我也很欣赏 python 中其他速记工具定义的链接。

回答by Imran

+=adds another value with the variable's value and assigns the new value to the variable.

+=将另一个值与变量的值相加,并将新值分配给变量。

>>> x = 3
>>> x += 2
>>> print x
5

-=, *=, /=does similar for subtraction, multiplication and division.

-=, *=,/=对减法、乘法和除法的作用类似。

回答by Kaleb Brasee

It adds the right operand to the left. x += 2means x = x + 2

它将右侧的操作数添加到左侧。 x += 2方法x = x + 2

It can also add elements to a list -- see this SO thread.

它还可以将元素添加到列表 - 请参阅此 SO 线程

回答by Ryan Bigg

+=adds a number to a variable, changing the variable itself in the process (whereas +would not). Similar to this, there are the following that also modifies the variable:

+=向变量添加一个数字,在过程中更改变量本身(而+不会)。与此类似,还有以下内容也修改了变量:

  • -=, subtracts a value from variable, setting the variable to the result
  • *=, multiplies the variable and a value, making the outcome the variable
  • /=, divides the variable by the value, making the outcome the variable
  • %=, performs modulus on the variable, with the variable then being set to the result of it
  • -=, 从变量中减去一个值,将变量设置为结果
  • *=, 将变量和一个值相乘,使结果成为变量
  • /=, 将变量除以值,使结果成为变量
  • %=, 对变量执行取模,然后将变量设置为其结果

There may be others. I am not a Python programmer.

可能还有其他人。我不是 Python 程序员。

回答by Bryan

In Python, += is sugar coating for the __iadd__special method, or __add__or __radd__if __iadd__isn't present. The __iadd__method of a class can do anything it wants. The list object implements it and uses it to iterate over an iterable object appending each element to itself in the same way that the list's extend method does.

在 Python 中,+= 是__iadd__特殊方法的糖衣,__add__或者__radd__如果__iadd__不存在。__iadd__类的方法可以做任何它想做的事情。列表对象实现它并使用它来迭代一个可迭代对象,以与列表的扩展方法相同的方式将每个元素附加到自身。

Here's a simple custom class that implements the __iadd__special method. You initialize the object with an int, then can use the += operator to add a number. I've added a print statement in __iadd__to show that it gets called. Also, __iadd__is expected to return an object, so I returned the addition of itself plus the other number which makes sense in this case.

这是一个实现__iadd__特殊方法的简单自定义类。您使用 int 初始化对象,然后可以使用 += 运算符添加一个数字。我在其中添加了一个打印语句__iadd__以显示它被调用。此外,__iadd__预计将返回一个对象,因此我返回了自身的加法以及在这种情况下有意义的另一个数字。

>>> class Adder(object):
        def __init__(self, num=0):
            self.num = num

        def __iadd__(self, other):
            print 'in __iadd__', other
            self.num = self.num + other
            return self.num

>>> a = Adder(2)
>>> a += 3
in __iadd__ 3
>>> a
5

Hope this helps.

希望这可以帮助。

回答by ZeroFunter

As others also said, the += operator is a shortcut. An example:

正如其他人所说, += 运算符是一种快捷方式。一个例子:

var = 1;
var = var + 1;
#var = 2

It could also be written like so:

也可以这样写:

var = 1;
var += 1;
#var = 2

So instead of writing the first example, you can just write the second one, which would work just fine.

因此,您可以编写第二个,而不是编写第一个示例,这会很好用。

回答by C S

It is not a mere syntactic shortcut. Try this:

这不仅仅是句法上的捷径。尝试这个:

x=[]                   # empty list
x += "something"       # iterates over the string and appends to list
print(x)               # ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']

versus

相对

x=[]                   # empty list
x = x + "something"    # TypeError: can only concatenate list (not "str") to list

This illustrates that += invokes the iaddlist method but + invokes add, which do different things with lists.

这说明 += 调用iaddlist 方法,而 + 调用add,它们对列表执行不同的操作。

回答by Roshan Mehta

x += 5is not exactly same as saying x = x + 5in Python.

x += 5x = x + 5Python 中的说法不完全相同。

Note here:

注意这里:

In [1]: x = [2,3,4]    
In [2]: y = x    
In [3]: x += 7,8,9    
In [4]: x
Out[4]: [2, 3, 4, 7, 8, 9]    
In [5]: y
Out[5]: [2, 3, 4, 7, 8, 9]    
In [6]: x += [44,55]    
In [7]: x
Out[7]: [2, 3, 4, 7, 8, 9, 44, 55]    
In [8]: y
Out[8]: [2, 3, 4, 7, 8, 9, 44, 55]    
In [9]: x = x + [33,22]    
In [10]: x
Out[10]: [2, 3, 4, 7, 8, 9, 44, 55, 33, 22]    
In [11]: y
Out[11]: [2, 3, 4, 7, 8, 9, 44, 55]

See for reference: Why does += behave unexpectedly on lists?

请参阅以供参考:为什么 += 在列表上表现出乎意料?

回答by salhin

Remember when you used to sum, for example 2 & 3, in your old calculator and every time you hit the =you see 3 added to the total, the +=does similar job. Example:

请记住,当您过去在旧计算器中进行求和时,例如 2 和 3,每次点击时,=您都会看到总数中增加了 3,结果+=类似。例子:

>>> orange = 2
>>> orange += 3
>>> print(orange)
5
>>> orange +=3
>>> print(orange)
8

回答by Vash

+=is just a shortcut for writing

+=只是写作的捷径

number = 4
number = number + 1

So instead you would write

所以你会写

numbers = 4
numbers += 1

Both ways are correct but example two helps you write a little less code

两种方式都是正确的,但示例二可以帮助您编写更少的代码

回答by plugwash

Notionally a += b "adds" b to a storing the result in a. This simplistic description would describe the += operator in many languages.

理论上 a += b 将 b “添加”到 a 中,将结果存储在 a 中。这种简单的描述将描述多种语言中的 += 运算符。

However the simplistic description raises a couple of questions.

然而,简单的描述引发了几个问题。

  1. What exactly do we mean by "adding"?
  2. What exactly do we mean by "storing the result in a"? python variables don't store values directly they store references to objects.
  1. 我们所说的“添加”究竟是什么意思?
  2. “将结果存储在 a 中”究竟是什么意思?python 变量不直接存储值,它们存储对对象的引用。

In python the answers to both of these questions depend on the data type of a.

在 python 中,这两个问题的答案都取决于 a 的数据类型。



So what exactly does "adding" mean?

那么“添加”究竟是什么意思呢?

  • For numbers it means numeric addition.
  • For lists, tuples, strings etc it means concatenation.
  • 对于数字,它意味着数字加法。
  • 对于列表、元组、字符串等,它意味着连接。

Note that for lists += is more flexible than +, the + operator on a list requires another list, but the += operator will accept any iterable.

请注意,对于列表 += 比 + 更灵活,列表上的 + 运算符需要另一个列表,但 += 运算符将接受任何可迭代对象。



So what does "storing the value in a" mean?

那么“将值存储在 a 中”是什么意思?

If the object is mutable then it is encouraged (but not required) to perform the modification in-place. So a points to the same object it did before but that object now has different content.

如果对象是可变的,则鼓励(但不要求)就地执行修改。所以 a 指向它之前所做的同一个对象,但该对象现在具有不同的内容。

If the object is immutable then it obviously can't perform the modification in-place. Some mutable objects may also not have an implementation of an in-place "add" operation . In this case the variable "a" will be updated to point to a new object containing the result of an addition operation.

如果对象是不可变的,那么它显然不能就地执行修改。一些可变对象也可能没有就地“添加”操作的实现。在这种情况下,变量“a”将被更新为指向一个包含加法运算结果的新对象。

Technically this is implemented by looking for __IADD__first, if that is not implemented then __ADD__is tried and finally __RADD__.

从技术上讲,这是通过__IADD__首先查找来实现的,如果未实现,则__ADD__尝试,最后__RADD__



Care is required when using += in python on variables where we are not certain of the exact type and in particular where we are not certain if the type is mutable or not. For example consider the following code.

在 python 中对我们不确定确切类型的变量使用 += 时需要小心,特别是当我们不确定类型是否可变时。例如,考虑以下代码。

def dostuff(a):
    b = a
    a += (3,4)
    print(repr(a)+' '+repr(b))

dostuff((1,2))
dostuff([1,2])

When we invoke dostuff with a tuple then the tuple is copied as part of the += operation and so b is unaffected. However when we invoke it with a list the list is modified in place, so both a and b are affected.

当我们使用元组调用 dostuff 时,元组将作为 += 操作的一部分进行复制,因此 b 不受影响。然而,当我们使用列表调用它时,列表会被修改,因此 a 和 b 都会受到影响。

In python 3, similar behaviour is observed with the "bytes" and "bytearray" types.

在 python 3 中,“bytes”和“bytearray”类型也观察到了类似的行为。



Finally note that reassignment happens even if the object is not replaced. This doesn't matter much if the left hand side is simply a variable but it can cause confusing behaviour when you have an immutable collection referring to mutable collections for example:

最后请注意,即使对象没有被替换,也会发生重新分配。如果左侧只是一个变量,这并不重要,但是当您有一个引用可变集合的不可变集合时,它可能会导致混乱的行为,例如:

a = ([1,2],[3,4])
a[0] += [5]

In this case [5] will successfully be added to the list referred to by a[0] but then afterwards an exception will be raised when the code tries and fails to reassign a[0].

在这种情况下,[5] 将成功添加到 a[0] 引用的列表中,但随后当代码尝试重新分配 a[0] 失败时将引发异常。