\begin{center} 关于 \texttt{\_\_getitem\_\_} 和 \texttt{\_\_len\_\_} 属于哪个模块? \end{center}

2024-10-03 23:27:46 发布

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

当我试图理解python上的“魔法”或特殊方法,并阅读this documentation时,我的印象是任何对象都会有这些方法

如果我们做一些简单的事情,比如

class ClassicSpam:
    pass

dir(ClassicSpam())

我得到的结果是:

['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']

我试图从类和继承的角度来理解这是如何工作的

是什么让我们在内部“知道”的任何履行本合同的调用self[key]都将调用object.__getitem__(self, key)

也许这不是正确的方法,我认为太像java了,但我想了解我遗漏了什么,以及在我实现的类中实现uu getitem_uu时会发生什么


Tags: 对象方法keyselfreduceinitdocumentationdir