doubly linked list 的长度实现,python

2024-04-25 17:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序调用len(list),len的定义如下。在

 def __len__(self):
    if not self.head:
        return '[]'
    else:
        return self.size

这是我得到的错误

^{pr2}$

所以基本上我必须在列表为空时返回“[]”,否则我需要返回它的长度。我该怎么做呢。在


Tags: self程序列表sizelenreturnif定义
2条回答

__len__应返回int>;=0。参见docs
错误就是这么说的。在

您返回的是一个字符串('[]'),它不是int,因此引发了此错误。
返回0将更合适。在

^{cd1>}的返回值必须是^{{cd2>}。因此,当列表为空时返回0。


docs开始:

object.__len__(self)

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

相关问题 更多 >