2021年6月10日 / 79次阅读 / Last Modified 2021年6月10日
Python对象中的__getitem__魔法函数的作用,就是可以在代码中,使用制定index([i])的方式来访问数据!
class Test(object):
# This function prints the type
# of the object passed as well
# as the object item
def __getitem__(self, keys):
print (type(keys), keys)
# Driver code
test = Test()
test[5]
test[5:65:5]
test['python.net']
test[1, 'x', 10.0]
test['a':'z':2]
test[object()]
运行效果:
<class 'int'=""> 5
<class 'slice'> slice(5, 65, 5)
<class 'str'> pynote.net
<class 'tuple'> (1, 'x', 10.0)
<class 'slice'> slice('a', 'z', 2)
<class 'object'>
你会发现,在[]内,基本上任何对象都可以使用。
numpy的ndarray的index方式为逗号(,),我一开始还在异或为什么多维数据的index方式跟多维list的方式不一样,现在懂了。
-- EOF --
本文链接:https://www.pynote.net/archives/3720
前一篇:for语句的iterator protocol
后一篇:一维ndarray
Ctrl+D 收藏本页
©Copyright 麦新杰 Since 2019 Python笔记