Magic methods let you change how your objects behave with built-in Python actions. They make your objects work like normal Python types.
Purpose of magic methods in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
def __method_name__(self, other): # your code here
Magic methods always start and end with double underscores.
They are called automatically by Python in special situations.
Examples
Python
def __str__(self): return 'Nice string representation'
Python
def __add__(self, other): return self.value + other.value
Python
def __len__(self): return len(self.items)
Sample Program
This program shows how magic methods __str__ and __add__ let us print boxes nicely and add their contents.
Python
class Box: def __init__(self, content): self.content = content def __str__(self): return f'Box with {self.content}' def __add__(self, other): return Box(self.content + ' & ' + other.content) box1 = Box('Apples') box2 = Box('Oranges') print(box1) print(box2) box3 = box1 + box2 print(box3)
Important Notes
Magic methods let your objects feel like built-in types.
You don't call magic methods directly; Python calls them for you.
Using magic methods makes your code cleaner and easier to use.
Summary
Magic methods customize how objects behave with Python features.
They always have double underscores before and after their name.
Common magic methods include __init__, __str__, __add__, and __len__.
Practice
1. What is the main purpose of magic methods in Python?
easy
Solution
Step 1: Understand what magic methods are
Magic methods are special functions with double underscores that let you change how objects act.Step 2: Identify their main use
They allow objects to work with Python features like printing, adding, or getting length.Final Answer:
To customize how objects behave with built-in Python features -> Option BQuick Check:
Magic methods = customize object behavior [OK]
Hint: Magic methods start and end with double underscores [OK]
Common Mistakes:
- Thinking magic methods create GUIs
- Confusing magic methods with file handling
- Believing magic methods are for comments
2. Which of the following is the correct syntax for a magic method that initializes an object?
easy
Solution
Step 1: Recall the correct magic method name for initialization
The magic method to initialize an object is spelled with double underscores before and after 'init'.Step 2: Check each option's syntax
Only 'def __init__(self):' has the correct double underscores and spelling.Final Answer:
def __init__(self): -> Option AQuick Check:
Initialization method = __init__ [OK]
Hint: Magic methods always have double underscores on both sides [OK]
Common Mistakes:
- Using single underscores instead of double
- Misspelling the method name
- Adding extra words like 'initialize'
3. What will be the output of this code?
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other.value
num1 = Number(5)
num2 = Number(10)
print(num1 + num2)medium
Solution
Step 1: Understand the __add__ magic method
The __add__ method defines how the + operator works for Number objects by adding their 'value' attributes.Step 2: Calculate the addition
num1.value is 5 and num2.value is 10, so 5 + 10 = 15.Final Answer:
15 -> Option CQuick Check:
__add__ adds values = 15 [OK]
Hint: __add__ defines + behavior for objects [OK]
Common Mistakes:
- Expecting string concatenation '510'
- Thinking it causes a TypeError
- Assuming it returns None
4. Identify the error in this code snippet:
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return name
p = Person('Alice')
print(p)medium
Solution
Step 1: Check the __str__ method's return value
The method returns 'name', but 'name' is not defined inside __str__; it should use self.name.Step 2: Understand variable scope
Since 'name' is undefined in __str__, this causes a NameError at runtime.Final Answer:
Using undefined variable 'name' in __str__ -> Option AQuick Check:
Use self.name inside methods [OK]
Hint: Use self.variable to access attributes inside methods [OK]
Common Mistakes:
- Forgetting self. before attribute names
- Thinking __str__ is misspelled
- Assuming no error occurs
5. You want to create a class where the length of an object returns the number of items it holds. Which magic method should you implement and how?
hard
Solution
Step 1: Identify the magic method for length
The built-in function len() calls the __len__ magic method on objects.Step 2: Confirm correct method name and purpose
Only __len__ is the correct magic method to return the number of items.Final Answer:
Implement __len__(self) to return the count of items -> Option DQuick Check:
len() calls __len__ [OK]
Hint: len() uses __len__ method inside objects [OK]
Common Mistakes:
- Using non-existent magic methods like __count__
- Confusing method names with similar words
- Not implementing any magic method
