__getitem__:+:'slice'和'int'

时间:2019-05-21 04:15:57

标签: python-3.x class-method operands

我正在使用this answer中的cirularbuffer实现。在大多数情况下,它运行正常。运行4天后,将导致以下错误。

File ..., line ... in __getitem__
    return(self._data[(key+self.index) % self.size])
TypeError: unsupported operand type(s) for +:'slice' and 'int' 

有问题的代码来自上面的链接:

def __getitem__(self, key):
    """Get element by index, relative to the current index"""
    if len(self._data) == self.size:
        return(self._data[(key + self.index) % self.size])
    else:
        return(self._data[key])

我不确定错误的确切含义。谁能给我一些启示?


self._data是该循环缓冲区类的内部列表。列表内容通过以下代码(cbuffer :: CircularList)设置:

if isinstance(rr, rrm.ReadHoldingRegistersResponse):
    self.cbuffer.append([ts, (bw_task.sta, bw_task.start, bw_task.length), rr.registers])

引起错误的相关代码如下:

block_buffer = list(block_buffer)
if len(block_buffer) > 0:
    table_data = self.process_rawdata_block(block_buffer, bw_task)
    # do db operation
    if len(table_data) > 0:
        self.save_to_db(table_data)
    else:
        print("DataMgr.loop.save_to_db: WARNING: empty table_data:", 
        "table_data=", table_data, "while block_buffer=", block_buffer, 
        "bw_task=", bw_task, "wkr.cbuff.length=", len(wkr.cbuffer))
else:
    print("wkr.cbuff.length=", len(wkr.cbuffer))
    if len(wkr.cbuffer) > 0:
        print("wkr.cbuff=", wkr.cbuffer[0:10])  # <---- Throw error in cbuffer.__getitem__()

1 个答案:

答案 0 :(得分:0)

很显然,我对 getitem 方法不了解,此答案通过示例进行了解释:Python: Implementing slicing in __getitem__

修复也很简单:

def __getitem__(self, key):
    """Get element by index, relative to the current index"""
    if len(self._data) == self.size:
        if isinstance(key, slice):
            return(self._data[(idx + self.index) % self.size] for idx in range(*key.indices(len(self._data))))
        return(self._data[(key + self.index) % self.size])
    else:
        if isinstance(key, slice):
            return(self._data[idx] for idx in range(*key.indices(len(self._data))))
        return(self._data[key])