程序园

一个Java 程序员的python学习之路9- __getite

2019-12-28  本文已影响0人  赵阳_c149

python中的和下划线有关的几种特殊方法

Python 中会用到下划线作为变量前缀和后缀指定特殊变量和方法,其中【1】:

__getitem__方法

__getitem__是object对象中的方法:object.__getitem__ (self, key)。python官方文档中对其作出了一下说明【3】

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

被调用以对self[key]求值。对于sequence类型,只接受整数和slice(切片)对象作为key。这里需要注意,对于负数索引的特殊解释取决于__getitem__() 方法。如果key是个不合适的类型,可能会抛出 TypeError;如果一个值超出了sequence对象索引的范围(在对负数值进行了特殊的解释之后),将抛出IndexError。对于mapping类型,如果key不在容器内,那么将抛出 KeyError

代码演示

class MyType(object):
    def __getitem__(self, item):
        return 'hello'

my_type = MyType()
print(my_type[1])

输出:

hello
my_dict['exist'] = 'exist_value'

print(my_dict['nonexist'])

输出:

Traceback (most recent call last):
  File "/Users/yangzhao/IdeaProjects/leetcode_python/src/queue/test_getitem.py", line 14, in <module>
    print(my_dict['nonexist'])
KeyError: 'nonexist'

【1】Python中特殊方法的分类与总结
【2】一个Java 程序员的python学习之路7- private 属性和方法
【3】object.__getitem__

上一篇 下一篇

猜你喜欢

热点阅读