所以当我尝试从我的类中获取我的列表的 len() 时,我得到了这个错误: TypeError: 'Stuff' 类型的对象没有 len() 当我尝试时:
>>> s = Stuff()
>>> len(s)
error instead of showing 0 like:
>>> l = []
>>> len(l)
0
代码:
class Stuff():
def __init__(self):
self.lst = []
最佳答案
定义__len__
像这样的特殊方法:
class Stuff():
def __init__(self):
self.lst = []
def __len__(self):
return len(self.lst)
现在你可以这样调用它:
>>> s = Stuff()
>>> len(s)
0
关于python - 如何从python中的类返回列表的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115831/