python __len__()方法

__len__()方法

python内置方法__len__()可以用于计算或统计python可迭代对象iterable的长度或元素个数,可以被不同的python可迭代对象调用。功能类似len()函数。


语法

Object.__len__(self, /)

python源码中对__len__()方法的介绍:

Return len(self).

参数

无。否则python抛出TypeError。


返回值

return len(self),即返回调用对象的长度或元素个数。python int类型值。


__len__()实例代码

>>> list1 = [1,2,3,4,5,6,7,8]
>>> list1.__len__()
8
>>> string = '笨鸟工具,x1y1z1.com'
>>> string.__len__()
15
>>> tup = (1,2,3)
>>> tup.__len__()
3
>>> dict1 = {'a':1,'b':2}
>>> dict1.__len__()
2
>>> set1 = set(list1)
>>> set1.__len__()
8
>>> range(9).__len__()
9
>>> list1.__len__(1) #传递参数给__len__()方法
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected 0 arguments, got 1
>>> num.__len__() #int类型并没有__len__属性
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__len__'

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.