在索引对象(如列表或元组)时是否发生函数调用?

2024-04-19 09:22:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能是一个愚蠢的问题,但我想知道,当我们有一个容器对象(如列表或元组)并对其进行索引时:

l = [2,4,5,6]
l[0]

在控制台中,我们得到:

out[#]: 2

如果我们这样做,我们也会得到同样的结果:

def ret(num):
    return num
ret(1)

当我们索引列表或元组等时,是否有隐藏的函数调用?你知道吗


Tags: 对象列表returndefoutnum容器元组
2条回答

是的;几乎所有对象上的操作都映射到特殊方法。在本例中是^{}方法。你知道吗

你的假设是正确的。Python有一些"magic methods",它们是使用相应的操作符从对象调用的。下标运算符([])就是其中之一。这个神奇的方法叫做^{}__getitem__()的文档提供了更多信息:

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.

您可以通过手动调用__getitem__()来观察它的工作方式:

>>> lst = [1, 2, 3, 4, 5]
>>> lst.__getitem__(0)
1
>>> lst.__getitem__(1)
2
>>> lst.__getitem__(2)
3
>>> # etc...

还有其他几种方法类似于__getitem__()^{}^{}__setitem__()将列表中的给定索引设置为给定值。调用方法的语法糖是sequence[index] = value。另一方面,__delitem__()删除给定索引处的值。它的语法糖是del sequence[index]。这两种方法都可以手动调用和观察:

>>> lst = [1, 2, 3, 4, 5]
>>> lst.__setitem__(0, 10)
>>> lst.__getitem__(0)
10
>>> lst.__delitem__(0)
>>> lst.__getitem__(0)
2
>>> 

资源

相关问题 更多 >