Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Appendix B. Python magic methods

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.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint