在Python中为自定义类实现add和iadd? [英] implementing add and iadd for custom class in python?

查看:306
本文介绍了在Python中为自定义类实现add和iadd?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Queue 类,该类包装了大部分操作的列表。但是我不从 list 订阅,因为我不想提供所有 list API的。我在下面粘贴了我的代码。 add 方法似乎可以正常工作,但 iadd 似乎出问题了,它没有打印。
这是代码:

I am writing a Queue class that wraps list for most of its operations. But I do not sublcass from list, since I do not want to provide all the list API's. I have my code pasted below. The add method seems to work fine, but iadd seems to go wrong, it is printing none. Here is the code:

import copy
from iterator import Iterator
class Abstractstruc(object):
    def __init__(self):
        assert False
    def __str__(self):
        return "<%s: %s>" %(self.__class__.__name__,self.container)

class Queue(Abstractstruc,Iterator):

    def __init__(self,value=[]):
        self.container=[]
        self.size=0
        self.concat(value)

    def add(self, data):
            self.container.append(data)
    def __add__(self,other):
        return Queue(self.container + other.container)


    def __iadd__(self,other):
        for i in other.container:
            self.add(i)

    def  remove(self):
        self.container.pop(0)


    def peek(self):
        return self.container[0]


    def __getitem__(self,index):
        return self.container[index]


    def __iter__(self):
        return Iterator(self.container)

    def concat(self,value):
        for i in value:
            self.add(i)

    def __bool__(self):
        return len(self.container)>0

    def __len__(self):
        return len(self.container)


    def __deepcopy__(self,memo):
        return Queue(copy.deepcopy(self.container,memo))


if __name__=='__main__':
    q5 = Queue()
    q5.add("hello")

    q6 = Queue()
    q6.add("world")

    q5 = q5+q6

    print q5
    q5+=q6
    print q5    

输出:

<Queue: ['hello', 'world']>
None


推荐答案

__iadd __ 在就地添加时需要返回 self

__iadd__ needs to return self when adding in-place:

def __iadd__(self,other):
    for i in other.container:
        self.add(i)
    return self

__ iadd __ 需要返回结果对象;对于不可变类型,新对象,对于可变类型, self 。引用就地操作符挂钩文档

__iadd__ needs to return the resulting object; for immutable types the new object, for mutable types, self. Quoting the in-place operator hooks documentation:


这些方法应尝试就地进行操作(修改 self )并返回结果(可以但不一定是 self )。

These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).

这篇关于在Python中为自定义类实现add和iadd?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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