Python中__getitem__()方法和索引器[]的详细用法

在本文中将详细描述如何使用Python为自定义对象使用索引器和类的__getitem__()方法;

索引器

在Python中,可使用索引器运算符[ ]来访问对象元素,例如字典mydict['name']

mydict['name']大致等同于mydict.__getitem__('name')

python允许你将任何对象传递到索引器中,例如:

test[5] #int 类型
test[2:10:-1] #切片
test[1:'string':object()] #任意类型的切片
test['name'] #字符串
test[123,'name',object,1,2,3,4,5] #任意数量、类型的参数

当传递给索引器的参数不止一个时,那么这些参数会被隐式的转换成元组;

比如test[1,'name']等同于 test[(1,'name')];而切片 test[1:2:3] 等同于test[slice(1,2,3)]

__getitem__()方法

任意类都可为其定义__getitem__()方法,该方法应定义一个参数用于接收传入到索引器的值;

该方法应返回一个值,省略则返回None;

示例代码

class Demo:

    def __getitem__(self,items):
        print(type(items),'---',items)
        if type(items) == int:
            return 123*2

test = Demo()

test[123]
test[1:10:-1]
test[345:"hello":object]
test[1,2,3,4,5,"string",print]
print("返回值为:",test[123])

程序输出

<class 'int'> --- 123
<class 'slice'> --- slice(1, 10, -1)
<class 'slice'> --- slice(345, 'hello', <class 'object'>)
<class 'tuple'> --- (1, 2, 3, 4, 5, 'string', <built-in function print>)
<class 'int'> --- 123
返回值为: 246

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/p/python-getitem.html

分类: 计算机技术
推荐阅读:
C++逐行读取文本文件 本文将使用C++实现逐行读取文本文件并显示;示例代码如下:
Rust实现线性搜索算法(Linear Search) 本文将使用Rust实现线性搜索算法(Linear Search);
Golang实现base64加密解密 Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。
ettercap扫描不到主机的解决方法 本文将详细讲解在Kali系统下使用Ettercap图形界面模式时扫描不到主机的问题,并提供问题排除方法;
System has not been booted with systemd as init system (PID 1). Can't operate.解决方法 在WSL(Windows Subsystem for Linux,适用于Linux的Windows子系统)下通过systemctl命令启动某些服务将造成System has not been booted with systemd as init system (PID 1). Can't operate.这样的错误;
Golang生成一个整数范围内的随机整数 在Golang中,可以通过math/rand包的Intn(n)函数生成一个0~n之间的随机整数,碰到100~200、-10~10这样的整数段却无能为力了;