特殊方法的 Python 文档在哪里? (__init__, __new__, __len__, ...)
哪里有可以在类中使用的特殊双下划线/dunder 方法的完整列表? (例如,__init__
、__new__
、__len__
、__add__
)
Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., __init__
, __new__
, __len__
, __add__
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
请查看 Python 中的特殊方法名称部分语言参考。
Please take a look at the special method names section in the Python language reference.
如果你像我一样想要一份简单、朴素的清单,那就在这里。我根据 Python 文档链接 编译了它接受的答案。
If, like me, you want a plain, unadorned list, here it is. I compiled it based on the Python documentation link from the accepted answer.
Dive Into Python 有一个优秀的附录
Dive Into Python has an excellent appendix for them.
如果您更喜欢从 CLI 而不是浏览器阅读文档,请执行此操作。
$ pydoc特殊方法
Do this if you prefer reading documentation from a CLI instead of the browser.
$ pydoc SPECIALMETHODS
请参阅 Python 快速参考
See Python Quick reference
对于那些对 Python 相对较新的人来说,文档通常不太容易访问(比如我自己):有人写了 很好的介绍,有很多关于特殊(魔术)方法如何工作、如何使用它们等的示例。
For somebody who is relatively new to Python, and for whom the documentation is often not quite accessible enough (like myself): somebody wrote a nice introduction with lots of examples on how the special (magic) methods work, how to use them, etc.
Python 的双下划线(“dunder”)方法也称为 datamodel 方法,因为它们是 Python 数据模型的核心,提供了用于自定义(重载)内置方法的协议。
这就是为什么它们被列在“数据模型”中的原因Python 文档的 部分。
Python's double underscore ("dunder") methods are also known as datamodel methods because they are at the core of Python's data model, providing a protocol for customizing (overloading) built-in methods.
This is the reason why they are listed in the "Data Model" section of the Python's documentation.
根据@Justin的回答,他包含了95个项目,以下是我可以推断出的dunder方法: # 105 on 2.7 and 108 on 3.10:
Output on 3.10:
Following on from @Justin's answer, he included 95 items, here are the dunder methods I could infer: # 105 on 2.7 and 108 on 3.10:
Output on 3.10:
熟悉 dir 函数。
Familiarize yourself with the dir function.