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

use*_*577 1 python

所以当我尝试从我的类中获取列表的len()时出现此错误:TypeError:当我尝试时,类型为'Stuff'的对象没有len():

>>> s = Stuff()
>>> len(s)
error instead of showing 0 like:
>>> l = []
>>> len(l)
0
Run Code Online (Sandbox Code Playgroud)

码:

class Stuff():
    def __init__(self):
        self.lst = []
Run Code Online (Sandbox Code Playgroud)

Vol*_*ity 5

__len__像这样定义特殊方法:

class Stuff():
    def __init__(self):
         self.lst = []
    def __len__(self):
         return len(self.lst)
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样调用它:

>>> s = Stuff()
>>> len(s)
0
Run Code Online (Sandbox Code Playgroud)