python 中的 __getitem__方法

python 中的 __getitem__方法,常见的两种写法

形式一: __getitem__(self, index) 一般用来迭代序列(常见序列如:列表、元组、字符串),或者求序列中的索引为 index 处的值。
形式二: __getitem__(self, key) 一般用来迭代映射(常见映射如:字典),或者求映射中的键为 key 出的值。

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

  • 对序列来说,索引应该是0~(n-1)的整数,其中n为序列的长度,一般写成 __getitem__(self, index)
  • 对于映射来说,假如键就是字典中的键,一般写成__getitem__(self, key)
如果在类中定义了__getitem__()方法,那么它的实例对象(假设为P)就可以这样P[index]取值或者这样P[key]取值。当实例对象做P[index或key]运算时,就会自动调用类中的__getitem__()方法。
# -*- coding:utf-8 -*-
class DataTest:
    def __init__(self,id,address):
        self.id=id
        self.address=address
        self.d={self.id:1,
                self.address:"192.168.1.1"
                }
        
    def __getitem__(self,key):
        return "hello"
    
 
data=DataTest(1,"192.168.2.11")
print data[2]	# 会自动调用 __getitem__方法

结果为:

hello
class Tag:
    def __init__(self):
        self.change={'python':'This is python'}
 
    def __getitem__(self, item):
        print('这个方法被调用')
        return self.change[item]
 
a=Tag()
print(a['python'])

结果为:

这个方法被调用
This is python

参考原文链接:
参考原文1
参考原文2

二、__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__ 都没有定义,这解释器就会报对象不是迭代器的错误:

TypeError: 'Animal' object is not iterable

而实现这个方法后,就可以正常迭代对象了。

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)

结果:

dog
cat
fish

参考原文链接:
参考原文3
参考原文4

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值