目录
一、该方法返回与指定索引(针对序列)或键(针对映射)相关联的值,使用 对象[index] 或者 对象[key] 将自动调用该方法。
前言
经常会遇到python类中遇到一些特殊的方法,最常见的就是__init__方法,想必大家都遇到过,今天来谈谈另外一种非常好用的类方法--__getitem__
__getitem__的作用是什么呢?说白了就是类中一个特殊方法,类对象可以像字典对象那样根据key取值(dict['key']),如类对象Object['key'],系统会自动调用__getitem__方法(所以你在看pytorch里面Dataloader的时候没有发现主函数直接调用__getitem__,原来是系统自动调用),然后返回该方法定义return值,说到这里,有一点需要强调哦, 字典取值时key不存在,会抛出异常,而类对象的key是否存在,都会调用__getitem__方法并返回其规定的值,下面进入实例。
常见写法
python 中的 __getitem__方法,常见的两种写法:
形式一: __getitem__(self, index) 一般用来迭代序列(常见序列如:列表、元组、字符串),或者求序列中的索引为 index 处的值。
形式二: __getitem__(self, key) 一般用来迭代映射(常见映射如:字典),或者求映射中的键为 key 出的值
一、该方法返回与指定索引(针对序列)或键(针对映射)相关联的值,使用 对象[index] 或者 对象[key] 将自动调用该方法。
- 对序列来说,索引应该是0~(n-1)的整数,其中n为序列的长度,一般写成 __getitem__(self, index)
- 对于映射来说,假如键就是字典中的键,一般写成__getitem__(self, key)
class DataTest():
def __init__(self, id, address):
self.id = id # 将传入的参数id和address分别赋值给类的实例变量self.id和self.address
self.address = address
self.d = {self.id: 1,
self.address: "192.168.1.1"
}
def __getitem__(self, key): #定义了特殊方法__getitem__,用于实现通过索引访问对象的功能
a=self.address[key]
return a
data = DataTest(1,"193.168.2.11")
print(data[2]) # 会自动调用 __getitem__方法
运行结果:
二、__getitem__方法,可以让对象实现迭代功能
Python中的__getitem__ 可以让对象实现迭代功能,这样就可以使用 for…in… 来迭代该对象了
class Animal:
def __init__(self, animal_list):
self.animals_name = animal_list
self.other = 'hello, world'
animals = Animal(["dog","cat","fish"])
for animal in animals:
print(animal)
在用 for…in… 迭代对象时,如果对象没有实现 __iter__ __next__ 迭代器协议,Python的解释器就会去寻找__getitem__ 来迭代对象,如果连__getitem__ 都没有定义,这解释器就会报对象不是迭代器的错误:
而实现这个方法后,就可以正常迭代对象了:
class Animal:
def __init__(self, animal_list):
self.animals_name = animal_list
self.other = 'hello, world'
def __getitem__(self, index):
return self.animals_name[index]
animals = Animal(["dog","cat","fish"])
for animal in animals:
print(animal)
运行结果: