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

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

    The return value of __iadd__() is used. You don't need to return the object that's being added to; you can create a new one and return that instead. In fact, if the object is immutable, you have to.

    import os.path
    
    class Path(str):
        def __iadd__(self, other):
            return Path(os.path.join(str(self), str(other)))
    
    path = Path("C:\\")
    path += "windows"
    
    print path
    

提交回复
热议问题