+ =在python中到底是做什么的?

问题:+ =在python中到底是做什么的?

我需要知道+ =在python中做什么。就这么简单。我也希望链接到python中其他速记工具的定义。

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.


回答 0

在Python中,+ =是__iadd__特殊方法的糖衣,__add__或者__radd__如果__iadd__不存在,则为+ 。__iadd__类的方法可以执行任何所需的操作。列表对象实现了它,并使用它来迭代一个可迭代对象,该对象将每个元素附加到自身上,方法与列表的extend方法相同。

这是一个实现__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

希望这可以帮助。

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.

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.

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


回答 1

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

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

-=*=/=做减法,乘法和除法类似。

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


回答 2

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

注意这里:

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]

请参阅以供参考:为什么+ =在列表上表现异常?

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

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?


回答 3

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

  • -=,从变量中减去一个值,将变量设置为结果
  • *=,将变量和一个值相乘,结果就是变量
  • /=,将变量除以值,使结果成为变量
  • %=,对变量执行模数,然后将变量设置为其结果

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

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


回答 4

它将右边的操作数添加到左边。 x += 2手段x = x + 2

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

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

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


回答 5

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

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

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

这说明+ =调用iadd list方法,而+调用add,后者对列表执行不同的操作。

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.


回答 6

通常,a + = b将b“加”到将结果存储到a中。这种简单的描述将以多种语言描述+ =运算符。

然而,简单的描述提出了两个问题。

  1. “添加”到底是什么意思?
  2. “将结果存储在a中”到底是什么意思?python变量不直接存储值,而是存储对对象的引用。

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


那么“加”到底是什么意思?

  • 对于数字,表示数字加法。
  • 对于列表,元组,字符串等,意味着串联。

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


那么“将值存储在”中意味着什么呢?

如果对象是可变的,则鼓励(但不是必需)就地执行修改。因此,指向以前做过的同一个对象,但是该对象现在具有不同的内容。

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

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


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

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

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

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

在python 3中,“ bytes”和“ bytearray”类型的行为类似。


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

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

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

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

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.

In python the answers to both of these questions depend on the data type of 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?

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.

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.

Technically this is implemented by looking for __IADD__ first, if that is not implemented then __ADD__ is tried and finally __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.

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.

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


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].


回答 7

简短的答案+=可以翻译为“将+ =右侧的任何内容添加到+ =“左侧的变量中。

例如 如果是a = 10这样的a += 5话: a = a + 5

因此,“ a”现在等于15。

The short answer is += can be translated as “add whatever is to the right of the += to the variable on the left of the +=”.

Ex. If you have a = 10 then a += 5 would be: a = a + 5

So, “a” now equal to 15.


回答 8

注意x += yx = x + y某些情况下包含附加运算符不同,这是因为运算符优先级加上总是首先评估右侧的事实,例如

>>> x = 2
>>> x += 2 and 1
>>> x
3

>>> x = 2
>>> x = x + 2 and 1
>>> x
1

注意第一种情况扩展为:

>>> x = 2
>>> x = x + (2 and 1)
>>> x
3

您更有可能在“现实世界”中与其他运营商(例如,

x *= 2 + 1== x = x * (2 + 1)!=x = x * 2 + 1

Note x += y is not the same as x = x + y in some situations where an additional operator is included because of the operator precedence combined with the fact that the right hand side is always evaluated first, e.g.

>>> x = 2
>>> x += 2 and 1
>>> x
3

>>> x = 2
>>> x = x + 2 and 1
>>> x
1

Note the first case expand to:

>>> x = 2
>>> x = x + (2 and 1)
>>> x
3

You are more likely to encounter this in the ‘real world’ with other operators, e.g.

x *= 2 + 1 == x = x * (2 + 1) != x = x * 2 + 1


回答 9

+= 只是写作的捷径

number = 4
number = number + 1

所以你会写

numbers = 4
numbers += 1

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

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


回答 10

就像其他人所说的,+ =运算符是快捷方式。一个例子:

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

也可以这样写:

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

因此,无需编写第一个示例,您只需编写第二个示例,就可以了。

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.


回答 11

请记住,当您过去使用旧计算器求和时(例如2和3),每当您点击=总和时,您就会看到3被加到总数中,+=执行类似的工作。例:

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

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:

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

回答 12

我看到很多使用+ =并带有多个整数的答案。

一个例子:

x -= 1 + 3

这类似于:

x = x - (1 + 3)

并不是:

x = (x - 1) + 3

I’m seeing a lot of answers that don’t bring up using += with multiple integers.

One example:

x -= 1 + 3

This would be similar to:

x = x - (1 + 3)

and not:

x = (x - 1) + 3

回答 13

根据文档

x += y等价于x = operator.iadd(x, y)。另一种表达方式是说它z = operator.iadd(x, y)等同于复合语句z = x; z += y

因此x += 3与相同x = x + 3

x = 2

x += 3

print(x)

将输出5。

请注意,还有

According to the documentation

x += y is equivalent to x = operator.iadd(x, y). Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y.

So x += 3 is the same as x = x + 3.

x = 2

x += 3

print(x)

will output 5.

Notice that there’s also