magic methods就是双下划线方法
As a Python developer who wants to harness the power of object-oriented programming, you’ll love to learn how to customize your classes using special methods, also known as magic methods or dunder methods. A special method is a method whose name starts and ends with a double underscore. These methods have special meanings for Python.
再谈(reprise) 三种下划线
- 单下划线在前一般用于声明私有成员,比如 _private_var
- 单下划线在后一般用于命名已经被保留关键字占用的变量,比如 class_,type_
- 双下划线一般被用于 Python 内置的特殊方法或者属性,比如 name,file,有时候也被称之为魔方方法。
Table of Contents
参考Python's Magic Methods: Leverage Their Power in Your Classes
- Getting to Know Python’s Magic or Special Methods
- Controlling the Object Creation Process
- Representing Objects as Strings
- Supporting Operator Overloading in Custom Classes
- Introspecting Your Objects
- Controlling Attribute Access
- Managing Attributes Through Descriptors
- Supporting Iteration With Iterators and Iterables
- Making Your Objects Callable
- Implementing Custom Sequences and Mappings
- Handling Setup and Teardown With Context Managers
- Conclusion
Reference
- Python's Magic Methods: Leverage Their Power in Your Classes
- Python中的下划线和魔方方法
- What is the meaning of single and double underscore before an object name?