__len__方法是一种常见的方法,顾名思义,主要用于判断某个类的长度。
定义Test类如下:
class Test(object):
def __init__(self):
self.num_list = [1, 2, 3]
def __len__(self):
return len(self.num_list)
执行
x = Test() # 下面两行等价 print(len(x.num_list)) print(x.__len__())
输出
3 3
由此可以看出__len__方法主要用于判断类中某属性的长度,只是直接调用len(x)时预设了输出某种属性的长度。
如果将代码改为:
class Test(object):
def __init__(self):
self.num_list = [1, 2, 3]
print(len(x))
则会输出
Traceback (most recent call last): File "xxx", line 9, inprint(x.__len__()) AttributeError: 'Test' object has no attribute '__len__'
博主会持续更新一些人工智能领域的知识和实践、工作中遇到的问题和感悟、高效工作的方法和技巧,如果喜欢请关注、点赞、收藏支持



