Summary of __getitem__() and __len__()

Summary of _getitem_ () and _len_ ( )

First define a function class

class Fun:
    def __init__(self, list):
        self.data = list
        print("init success")
    
    def __getitem__(self, idx):
        print("__getitem__ is called")
        return self.data[idx]
    
    def __len__(self):
        print("__len__ is called")
        return len(self.data)

instantiated class

fun = Fun([1, 2, 3, 4, 5])

# 输出:init success
1. _titled_ ()

run the following code

print(fun[2])

# 输出:
# __getitem__ is called
# 3

__getitem__()The method receives an idx parameter, which is 2 in fun[2], which is the index value given by itself. When the statement fun[2] appears, __getitem__(self,idx) will be triggered, and this method will return self.data[2].

If the return statement is removed, __getitem__()the method is changed to

def __getitem__(self, idx):
    print("__getitem__ is called")

Then no matter what parameter idx receives, it will output as follows

print(fun['6']) # 或者 print(fun[6])

# 输出:
# __getitem__ is called
# None
2. _len_()

Python contains a built-in method len(), which can be used to measure the length of sequence objects such as list and tuple, as follows:

num = [1,2,3,4,5]
print(len(num))

# 输出: 5

Define a method in a class __len__(), and you can measure the length of an instance attribute by using len()a function on the instance object to call the method in the class __len__(), as shown below

print(len(fun))

# 输出:
# __len__ is called
# 5

Guess you like

Origin blog.csdn.net/weixin_48319333/article/details/130163953