在python中+=具体做什么?

时间:2022-01-13 11:59:12

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中可以链接到其他简短工具的定义。

10 个解决方案

#1


85  

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__方法可以做任何它想做的事情。list对象实现了它,并使用它在一个可迭代的对象上迭代,该对象将每个元素附加到自己,其方式与list的扩展方法相同。

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__中添加了一个print语句来显示它被调用。而且,__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.

希望这个有帮助。

#2


64  

+= 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.

-=、*=、/=在减法、乘法和除法上做的类似。

#3


17  

+= 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程序员。

#4


15  

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

它在左边添加右操作数。x += 2表示x = x + 2

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

它还可以向列表添加元素——请参见SO thread。

#5


13  

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 iadd list method but + invokes add, which do different things with lists.

这说明了+=调用iadd list方法,但是+调用add,它对列表做不同的事情。

#6


11  

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

x += 5与Python中的x = x + 5并不完全相同。

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?

参见参考:为什么+=在列表上执行意外?

#7


3  

+= 

is just a shortcut for writing

这只是写作的捷径吗

numbers = 1
numbers = numbers + 1
print (numbers)   ## 2

So instead you would write

所以你会写。

numbers = 1
numbers += 1
print (numbers)   ## 2

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

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

#8


2  

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中存储结果。这个简单的描述将在许多语言中描述+=运算符。

However the simplistic description raises a couple of questions.

然而,过于简单的描述引出了几个问题。

  1. What exactly do we mean by "adding"?
  2. “添加”到底是什么意思?
  3. What exactly do we mean by "storing the result in a"? python variables don't store values directly they store references to objects.
  4. “将结果存储在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.

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

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

在python 3中,“字节”和“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]将成功地添加到[0]所引用的列表中,但是,当代码尝试并没有重新分配[0]时,将会引发异常。

#9


-1  

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.

所以不写第一个例子,你可以写第二个,这样就行了。

#10


-1  

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

#1


85  

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__方法可以做任何它想做的事情。list对象实现了它,并使用它在一个可迭代的对象上迭代,该对象将每个元素附加到自己,其方式与list的扩展方法相同。

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__中添加了一个print语句来显示它被调用。而且,__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.

希望这个有帮助。

#2


64  

+= 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.

-=、*=、/=在减法、乘法和除法上做的类似。

#3


17  

+= 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程序员。

#4


15  

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

它在左边添加右操作数。x += 2表示x = x + 2

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

它还可以向列表添加元素——请参见SO thread。

#5


13  

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 iadd list method but + invokes add, which do different things with lists.

这说明了+=调用iadd list方法,但是+调用add,它对列表做不同的事情。

#6


11  

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

x += 5与Python中的x = x + 5并不完全相同。

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?

参见参考:为什么+=在列表上执行意外?

#7


3  

+= 

is just a shortcut for writing

这只是写作的捷径吗

numbers = 1
numbers = numbers + 1
print (numbers)   ## 2

So instead you would write

所以你会写。

numbers = 1
numbers += 1
print (numbers)   ## 2

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

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

#8


2  

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中存储结果。这个简单的描述将在许多语言中描述+=运算符。

However the simplistic description raises a couple of questions.

然而,过于简单的描述引出了几个问题。

  1. What exactly do we mean by "adding"?
  2. “添加”到底是什么意思?
  3. What exactly do we mean by "storing the result in a"? python variables don't store values directly they store references to objects.
  4. “将结果存储在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.

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

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

在python 3中,“字节”和“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]将成功地添加到[0]所引用的列表中,但是,当代码尝试并没有重新分配[0]时,将会引发异常。

#9


-1  

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.

所以不写第一个例子,你可以写第二个,这样就行了。

#10


-1  

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