English documents:
Len (s)
Return the length (the number of items) of an object. The argument may is a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set , or frozen set).
Description
1. Returns the length of an object, which can be a sequence (such as a string, byte array, tuple, list, and Range object), or a collection (such as a dictionary, collection, immutable collection)
>>> len (' ABCD ') # string >>> len (bytes (' ABCD ', ' Utf-8 ')) # byte array >>> len ((1,2,3,4)) # tuple >> > len ([1,2,3,4]) # list >>> len (range 1,5) # Range object >>> len ({' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}) # dictionary >>& Gt Len ({' A ', ' B ', ' C ', ' d '}) # collection >>> len (Frozenset (' ABCD ')) #不可变集合
2. If the parameter is a different type, it must implement the __len__ method and return an integer, otherwise an error.
>>> class A: def __init__ (self,name): self.name = name def __len__ (self): return Len ( Self.name) >>> a = A (") >>> Len (a) >>> a = A (' Aim ') >>> Len (a) >>> class B: pass>>> B = B () >>> Len (b) Traceback (most recent call last): File "
", line 1, in
len (b) Typeerror:object of type ' B ' have no Len () >>> class C:
def __len__ (self): return ' len ' >>> C = C () >>> Len (c) Traceback (most recent call last): File "
", line 1, in
len (c) TypeError: ' str ' object cannot is interpreted as an INTEGER