python中 __getitem__ 的使用

目录

前言

常见写法

一、该方法返回与指定索引(针对序列)或键(针对映射)相关联的值,使用 对象[index] 或者 对象[key] 将自动调用该方法。

二、__getitem__方法,可以让对象实现迭代功能


前言

经常会遇到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)

运行结果:

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值