简体   繁体   English

在Python中为自定义类实现add和iadd?

[英]implementing add and iadd for custom class in python?

I am writing a Queue class that wraps list for most of its operations. 我正在编写一个Queue类,该类包装了大多数操作的列表。 But I do not sublcass from list , since I do not want to provide all the list API's . 但是我不从list删除,因为我不想提供所有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. add方法似乎可以正常工作,但是iadd似乎出错,它没有打印任何内容。 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    

Output: 输出:

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

__iadd__ needs to return self when adding in-place: __iadd__在就地添加时需要返回self

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

__iadd__ needs to return the resulting object; __iadd__需要返回结果对象; for immutable types the new object, for mutable types, self . 对于不可变类型,新对象,对于可变类型, self Quoting the in-place operator hooks documentation : 引用就地操作员挂钩文档

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 ). 这些方法应尝试就地进行操作(修改self )并返回结果(可以是,但不一定必须是self )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM