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

后端 未结 4 1753
故里飘歌
故里飘歌 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:00

    class aug_int:
        def __init__(self, value):
            self.value = value
    
        def __iadd__(self, other):
            self.value += other
            return self
    
    >>> i = aug_int(34)
    >>> i
    <__main__.aug_int instance at 0x02368E68>
    >>> i.value
    34
    >>> i += 55
    >>> i
    <__main__.aug_int instance at 0x02368E68>
    >>> i.value
    89
    >>>
    

提交回复
热议问题