__getitem__的作用

 __getitem__本质上将一个对象具有字典功能

案例一:

class Text__getitem__():
    def __init__(self):
        pass
    def __len__(self):
        return 3
    def __getitem__(self, key):
        if key.startswith("abc"):
            return "abc"
        elif key.startswith("bcd"):
            return "bcd"
        else:
            return "nonono"
obj = Text__getitem__()
print(obj["abc"])

输出:abc

案例二:

class Text__getitem__():
    def __init__(self):
        pass
    def __len__(self):
        return 3
    def __getitem__(self, key):
        if key.startswith("abc"):
            return "abc"
        elif key.startswith("bcd"):
            return "bcd"
        else:
            return "nonono"
obj = Text__getitem__()
print(obj["abc"])

for k, v in enumerate(obj):
    print(k, v)

输出:
abc
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-90-24e3e74a5609> in <module>
     14 print(obj["abc"])
     15 
---> 16 for k, v in enumerate(obj):
     17     print(k, v)

<ipython-input-90-24e3e74a5609> in __getitem__(self, key)
      5         return 3
      6     def __getitem__(self, key):
----> 7         if key.startswith("abc"):
      8             return "abc"
      9         elif key.startswith("bcd"):

AttributeError: 'int' object has no attribute 'startswith'

案例三:

class Text__getitem__():
    def __init__(self):
        pass
    def __len__(self):
        return 3
    def __getitem__(self, key):
        if key < 0 or key >= 3: 
            raise IndexError
        if key == 1:
            return "abc"
        elif key == 2:
            return "bcd"
        else:
            return "nonono"
obj = Text__getitem__()
for k, v in enumerate(obj):
    print(k, v)

输出:
0 nonono
1 abc
2 bcd

这两句代码非常重要,否则就会key值就会一直循环下去。
if key < 0 or key >= 3: 
    raise IndexError

案例四、

class Text__getitem__():
    def __init__(self):
        pass
    def __len__(self):
        return 3
    def __getitem__(self, key):
        if key == 1:
            return "abc"
        elif key == 2:
            return "bcd"
        else:
            return "nonono"
obj = Text__getitem__()
for k, v in enumerate(obj):
    print(k, v)

输出:
0 nonono
1 abc
2 bcd
3 nonono
4 nonono
5 nonono
6 nonono
7 nonono
8 nonono
9 nonono
10 nonono
11 nonono
12 nonono
13 nonono
14 nonono
15 nonono
16 nonono
17 nonono
18 nonono
19 nonono
20 nonono
21 nonono
……

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值