调用len([1,2,3])
和[1,2,3].__len__()
有什么区别吗?
如果没有明显的区别,那么在幕后有什么不同的做法呢?
发布于 2010-03-20 08:57:02
len
是一个获取集合长度的函数。它通过调用对象的__len__
方法来工作。__something__
属性很特殊,通常看起来很复杂,通常不应该直接调用。
在很久以前的某个时刻,人们就已经决定,获取某个东西的长度应该是一个函数,而不是一个方法代码,因为len(a)
的含义对初学者来说是很清楚的,但a.len()
就不那么清楚了。当Python开始的时候,__len__
甚至还不存在,而len
是一个可以处理几种类型对象的特殊东西。无论这种情况是否完全有意义,它都会一直存在。
发布于 2010-03-20 09:02:20
您可以认为len()大致等同于
def len(x):
return x.__len__()
它的一个优点是,它允许您编写如下内容
somelist = [[1], [2, 3], [4, 5, 6]]
map(len, somelist)
而不是
map(list.__len__, somelist)
或
map(operator.methodcaller('__len__'), somelist)
不过,两者的行为略有不同。例如,在in的情况下
>>> (1).__len__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__len__'
>>> len(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
发布于 2015-02-18 17:23:48
你可以查看Pythond docs
>>> class Meta(type):
... def __getattribute__(*args):
... print "Metaclass getattribute invoked"
... return type.__getattribute__(*args)
...
>>> class C(object):
... __metaclass__ = Meta
... def __len__(self):
... return 10
... def __getattribute__(*args):
... print "Class getattribute invoked"
... return object.__getattribute__(*args)
...
>>> c = C()
>>> c.__len__() # Explicit lookup via instance
Class getattribute invoked
10
>>> type(c).__len__(c) # Explicit lookup via type
Metaclass getattribute invoked
10
>>> len(c) # Implicit lookup
10
https://stackoverflow.com/questions/2481421
复制相似问题