Python __setattr__() Magic Method

3/5 - (3 votes)

Python’s magic method __setattr__() implements the built-in setattr() function that takes an object and an attribute name as arguments and removes the attribute from the object.

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Syntax and Minimal Example

object.__setattr__(self, attr_name, attr_value)

Let’s have a look at an example where you override the __setattr__ magic method of a custom class Person to simply print out the arguments rather than really changing the attributes of the class as the default setattr() function would do:

class Person:
    def __setattr__(self, attr_name, attr_value):
        print(attr_key, attr_value)
    

alice = Person()
setattr(alice, 'age', 32)
# age 32

💡Note that if you wouldn’t have overridden the __setattr__() magic method, Python would’ve created a new attribute for the alice instance, so when calling alice.age, you’d have obtained the value 32.

You can see this scenario next in our recap on the built-in setattr() function.

Background setattr()

Python’s built-in setattr(object, string, value) function takes three arguments:

  • an object,
  • a string, and
  • an arbitrary value.

It sets the attribute given by the string on the object to the specified value.

After calling the function, there’s a new or updated attribute at the given instance, named and valued as provided in the arguments.

For example, setattr(object, 'attribute', 42) is equivalent to object.attribute = 42.

Before we dive into another practical example of the setattr() function, feel free to watch my explainer video here:

Python setattr() - The Ultimate Guide

Let’s dive into an example next.

In object-oriented programming, you can often see the use of the setattr() built-in function in combination with the object self in the __init__() initializer method.

The idea is to create a class with dynamic attributes chosen at runtime by the user or the program. This way, you can create container classes that hold arbitrary attributes.

class Person:
    def __init__(self, attributes):
        for key, value in attributes.items():
            setattr(self, key, value)


# Create two different persons
alice = Person({'name': 'Alice', 'income': 180000, 'eyes': 'blue'})
bob = Person({'firstname': 'Max', 'lastname': 'Power'})


# Different persons, different attributes
print(alice.name + ' ' + str(alice.income) + ' ' + alice.eyes)
print(bob.firstname + ' ' + bob.lastname)


# Output:
'''
Alice 180000 blue
Max Power
'''

This is a convenient way to create classes with different attribute names.

References:

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.

Join the free webinar now!