__getitem__()和__len__()总结

_getitem_()及_len_()总结

先定义一个函数类

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)

实例化类

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

# 输出:init success
1. _getitem_()

运行下面代码

print(fun[2])

# 输出:
# __getitem__ is called
# 3

__getitem__()方法接收一个idx参数,这个参数就是fun[2]中的2,也就是自己给的索引值。当fun[2]这个语句出现时,就会触发__getitem__(self,idx),这个方法就会返回self.data[2]。

如果去掉return语句,__getitem__()方法改为

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

那么idx无论接收什么参数,都是如下输出

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

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

python包含一个内置方法len(),使用它可以测量list、tuple等序列对象的长度,如下:

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

# 输出: 5

在类中定义__len__()方法,能通过对实例对象使用len()函数来调用类中的__len__()方法,来测量某个实例属性的长度,如下所示

print(len(fun))

# 输出:
# __len__ is called
# 5

猜你喜欢

转载自blog.csdn.net/weixin_48319333/article/details/130163953