Magic/Dunder Methods in Python 🎯

beginner
12 min

Magic/Dunder Methods in Python 🎯

Welcome to our deep dive into Python's Magic Methods, also known as Dunder Methods! These methods are special functions in Python that have a double underscore __ before and after their names. They let you create custom behavior for your objects, making them a powerful tool in object-oriented programming. Let's get started! 📝

Understanding Dunder Methods 💡

Dunder methods are called implicitly by Python when certain operations are performed on an object. They allow you to customize how your classes respond to these operations. Let's break it down:

  • __ is a special prefix for these methods, making them identifiable.
  • The methods are called dunder because they have this special double underscore prefix and suffix.
  • The methods are implicitly called by Python when certain operations are performed on an object.

Basic Dunder Methods 💡

Here are some of the basic dunder methods you'll come across:

__init__

This is the constructor method that initializes the object. It is called when an object is created.

python
class Person: def __init__(self, name, age): self.name = name self.age = age person = Person('John', 25) print(person.name) # Output: John

__str__

This method is used when we want to print the object. It returns a string representation of the object.

python
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'Person: {self.name}, Age: {self.age}' person = Person('John', 25) print(person) # Output: Person: John, Age: 25

__repr__

This method is similar to __str__, but it is used for getting the object's printable representation when it is used in the context of a code. For example, in an interactive shell or in the print() function.

python
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f'Person({self.name!r}, {self.age})' person = Person('John', 25) print(person) # Output: Person('John', 25)

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `__init__` method do in Python?

Advanced Dunder Methods 💡

Here are some advanced dunder methods that will help you create more complex and flexible objects:

__getattr__ and __setattr__

These methods allow you to customize the way attributes are accessed and modified for your objects.

python
class Person: def __init__(self, name): self.name = name def __getattr__(self, attr): if attr == 'age': return 25 raise AttributeError(f"'Person' object has no attribute '{attr}'") def __setattr__(self, key, value): print(f'Setting attribute {key} to {value}') super().__setattr__(key, value) person = Person('John') print(person.age) # Output: 25 person.age = 30 print(person.age) # Output: 30

__call__

This method allows your object to be called as a function.

python
class Adder: def __init__(self): self.total = 0 def __call__(self, *numbers): self.total += sum(numbers) return self.total adder = Adder() print(adder(1, 2, 3)) # Output: 6 print(adder(4, 5)) # Output: 10

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `__getattr__` method do in Python?

Wrapping Up ✅

Dunder methods are a powerful tool in Python, allowing you to customize the behavior of your classes and objects. By understanding and using them, you can create more flexible and reusable code. Keep experimenting, and happy coding! 💻💼