今日已更新 138 条资讯 | 累计 31816 条内容
关于我们

Python Data Model - Part 2: Protocols and Special Methods

Bruno Teixeira Lopes 2026年08月15日 02:54 0 次阅读 来源:Dev.to

🌐 Leia a versão em português deste artigo aqui . 1. From Part One to Language Protocols In Part 1 , we established the foundation of Python's data model: objects possess identity, type, and value; names hold references to those objects; mutability determines what changes can occur without replacing the object; and containers store references to other objects. Now we advance another layer. The type of an object does not merely determine what values it can represent. It also determines which operations that object supports : whether it has a size, whether it can be traversed, compared, indexed, called as a function, used in a with statement, and so forth (PYTHON SOFTWARE FOUNDATION, 2026a). This is where special methods come in. An important observation before we continue: in Part 1 we used memory address as a mental model for identity. More rigorously, Python guarantees that an object's identity remains stable during its existence. In CPython specifically, id(obj) corresponds to the memory address of the object; this is a detail of the reference implementation, not a language guarantee (PYTHON SOFTWARE FOUNDATION, 2026a). The same distinction will be important when we discuss garbage collection and finalization: Python specifies the language's behavior; CPython is one implementation of that behavior . Reference Version The behaviors and references in this article were reviewed based on the official documentation of Python 3.14.7 . CPython-specific details will be explicitly identified. 2. What Are Special Methods In the official documentation, names like __len__ , __iter__ , and __add__ are called special methods . In the community, you will also commonly find the terms magic methods or dunder methods ( dunder comes from double underscore because of the __name__ pattern). They allow classes defined by us to participate in operations that are part of the language's own syntax and built-in functions. For example: You write Behavior Python must resolve Related methods r

本文内容来源于互联网,版权归原作者所有
查看原文