Skip to main content
 首页 » 编程设计

python之如何从python中的类返回列表的长度

2025年05月04日17shihaiming

所以当我尝试从我的类中获取我的列表的 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