Search This Blog

python: len() function and __len__() method

len is a function to get the length of a collection. It works by calling an object's __len__ method.

class AClass(object):
def __init__(self):
self._list = [1,2,3]

def __len__(self):
return len(self._list)

a=AClass()
print(a.__len__()) # 3
print(len(a)) # 3

No comments:

Post a Comment