bra*_*orm 0 python class add object in-place
我正在编写一个Queue包含大多数操作列表的类.但是我不会从中升级list,因为我不想提供所有的list API's.我的代码粘贴在下面.该add方法似乎工作正常,但iadd似乎出错,它打印没有.这是代码:
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
Run Code Online (Sandbox Code Playgroud)
输出:
<Queue: ['hello', 'world']>
None
Run Code Online (Sandbox Code Playgroud)
__iadd__self在就地添加时需要返回:
def __iadd__(self,other):
for i in other.container:
self.add(i)
return self
Run Code Online (Sandbox Code Playgroud)
__iadd__需要返回结果对象; 对于不可变类型,新对象,对于可变类型,self.引用就地操作符挂钩文档:
这些方法应该尝试就地进行操作(修改
self)并返回结果(可能是,但不一定是这样self).
| 归档时间: |
|
| 查看次数: |
1132 次 |
| 最近记录: |