Appendix B. Python magic methods

 

Creating your own objects in Python inevitably means implementing one or more of Python’s protocol methods—the magic methods whose names start and end with double underscores. These protocols are roughly the equivalent of interfaces in Python.

The lookup rules for the magic methods are slightly different from those of other attributes. Normal attribute lookup order[1] is instance -> class -> base classes. Magic method lookup goes directly to the class, skipping the instance. This means that you can’t override these methods by attaching a function directly to the instance (or through __getattr__); overriding has to happen at the class level. To provide these methods for classes themselves, they need to be implemented on the classes’ class, that is, its metaclass.[2]

1 This order assumes the usual caveat that the descriptor protocol makes the full lookup rules more complex. Section B.9 of this appendix describes the descriptor protocol.

2 The IronPython generics support using the Array[int] syntax, which is implemented by adding a __getitem__ method to the type metaclass.

This appendix is a reference to all the common magic methods.[3]

3 This is only a summary; for full details refer to the Python documentation at http://docs.python.org/index.html.

B.1. Object creation

The object creation methods are called when a class is instantiated, as shown in table B.1.

B.2. Comparison

B.3. Miscellaneous

B.4. Containers and iteration

B.5. Conversion to string

B.6. Attribute access

B.7. Numeric types

B.8. Context managers and the with statement

B.9. The descriptor protocol

B.10. Magic attributes

B.11. Functions and modules