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__(self,key)

点击查看代码
# -*- 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

二、
__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)

结果:

TypeError: 'Animal' object is not iterable

在用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)
结果:
点击查看代码
dog
cat
fish

https://blog.csdn.net/weixin_45580017/article/details/124553851

posted @   阳光天气  阅读(403)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示