+ =在python中到底是做什么的? [英] What exactly does += do in python?

查看:286
本文介绍了+ =在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.

推荐答案

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

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.

这是一个实现__iadd__特殊方法的简单自定义类.您可以使用int初始化对象,然后可以使用+ =运算符添加数字.我在__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.

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

希望这会有所帮助.

这篇关于+ =在python中到底是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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