Get startedGet started for free

Customizing attribute assignment with __setattr__

Previously, we used descriptors to implement logic that was run when a specific attribute was retrieved, set, or deleted. But what if we'd like to make sure a certain block of code runs each time any attribute is set? In this exercise, you'll practice doing this with a Python magic method.

This exercise is part of the course

Intermediate Object-Oriented Programming in Python

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

class BankAccount:
  def __init__(self, account_number):
    self.account_number = account_number
  
  # Define a method to be executed when setting attributes
  def ____(self, ____, ____):
    pass
Edit and Run Code