- 为什么会有人使用双下划线
- 为什么不直接执行
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 functionlen(). 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.
