Contribute Media
A thank you to everyone who makes this possible: Read More

The Magic of Self: How Python inserts self into methods

Translations: en

Description

Have you ever wondered how self works? Whenever you call a method, self seems to magically appear as an argument. But behind this dark magic lies a well-defined protocol, the descriptor protocol, that you can implement yourself. Join me and learn how Python inserts self into methods!

A phrase that I hear a lot is that “Python is easy to learn but hard to master”. In a way that’s true: Python’s many abstractions allow you to focus on the business logic of your code instead of the lower-level implementation details.

At the same time, most of Python’s abstractions aren’t magical: Its versatile data model allows you to hook into almost every aspect of the language to implement objects that behave just as Python’s built-in objects do. This enables you to create new types of objects that have high-level interfaces of their own.

In this talk, I want to entice you to explore the wonderful landscape of Python’s data model by diving into an especially magical feature: The automatic insertion of self into methods.

When you first came across self in a method signature, chances are that you learned that inserting the instance into methods is just something Python does for you; that you shouldn’t worry too much about it. I will go one step further and show you that there’s a well-defined protocol behind this magic, the descriptor protocol.

By the end, not only should you be able to implement descriptors of your own, but you should also be able to recognize that some well-known features of Python, such as properties and classmethods, are implemented using the same descriptor protocol.

Details

Improve this page