Python’s __set__()
magic method sets a given attribute on an instance of a class holding the attribute (=owner class) to a new value. When setting the attribute through the owner class, Python dynamically executes the attribute’s __set__()
method to override its value
on the given instance
argument.
object.__set__(self, instance, value)
For example, if you create a class Person
with an attribute of type Name
(and instances person
and name
), setting person.name = 42
would result in calling the Name
‘s __set__()
method to obtain the result.
💡 Terminology: The name
attribute of type Name
in our example is called a descriptor.
Minimal Example
In the following, you can see a minimal example of a descriptor name
attribute defining the __set__
magic method.
class Name: def __set__(self, instance, value): self.value = value class Person: name = Name() alice = Person() # The following calls __set__(alice.name, 'Alice Python'): alice.name = 'Alice Python' print(alice.name.value) # Alice Python
Let’s go through the code next:
- You create a
Person
class with one attribute name of typeName
. - You define the
Name
class as a descriptor by overriding the__set__
magic method. - The
__set__
method takes over responsibility each time you’re about to assign a value to an attribute of typeName
. - Python translate the expression
alice.name = 'Alice Python'
to__set__(alice.name, 'Alice Python')
. - In this magic method call, you set the
name.value
attribute to the string'Alice Python'
passed as an argument. This is the output of this code snippet.
Now, you have an initial intuition. To learn more about how descriptors work, I’d recommend you check out the in-depth official Python tutorial that is a great resource on the topic! 🙂
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.