python:__getitem__方法详解

__getitem__(self,key):

这个方法返回与指定键想关联的值。对序列来说,键应该是0~n-1的整数,其中n为序列的长度。对映射来说,键可以是任何类型。

class Tag:
    def __init__(self,id):
        self.id=id

    def __getitem__(self, item):
        print('这个方法被调用')
        return self.id

a=Tag('This is id')
print(a.id)
print(a['python'])

输出:

This is id
这个方法被调用
This is id

这验证了上边的话,如果是映射的话,键可以是任意类型,序列的n无论是多少,__getitem__总是会被调用

但是事实上这样是不规范的,我们应该这样做

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'])

猜你喜欢

转载自blog.csdn.net/weixin_42557907/article/details/81589574