Skip to main content
 首页 » 编程设计

python:这个有趣的符号是什么 [0,1,3].__len__()

2025年05月04日10shangdawei

  1. 为什么会有人使用双下划线
  2. 为什么不直接执行 len([1,2,3])?

我的问题具体是下划线是什么意思?

请您参考如下方法:

__len__() 是使用 len() 时调用的特殊 Python 方法。

这很像 str() 使用 __str__(),repr 使用 __repr__() 等. 您可以在您的类中重载它,以便在您的类的实例上使用时为 len() 提供自定义行为。

参见此处:http://docs.python.org/release/2.5.2/ref/sequence-types.html :

__len__(self)
Called to implement the built-in function len(). Should return the length of the object, an integer >= 0.
Also, an object that doesn't define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context.