How to implement “__iadd__()” for an immutable type?

后端 未结 4 1760
故里飘歌
故里飘歌 2020-12-19 18:24

I would like to subclass an immutable type or implement one of my own which behaves like an int does as shown in the following console session:



        
4条回答
  •  不知归路
    2020-12-19 19:09

    Simply don't implement __iadd__, but only __add__:

    >>> class X(object):
    ...     def __add__(self, o):
    ...             return "added"
    >>> x = X()
    >>> x += 2
    >>> x
    'added'
    

    If there's no x.__iadd__, Python simply calculates x += y as x = x + y doc.

提交回复
热议问题