0
0
Pythonprogramming~10 mins

Purpose of magic methods in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Purpose of magic methods
Create object
Call method or operation
Python looks for magic method
If found, execute magic method
Return result or perform action
Continue program
When you use built-in operations on objects, Python looks for special magic methods to decide how to behave.
Execution Sample
Python
class Box:
    def __init__(self, size):
        self.size = size
    def __str__(self):
        return f"Box of size {self.size}"

b = Box(5)
print(b)
This code shows how the __str__ magic method controls what print(b) outputs.
Execution Table
StepActionEvaluationResult
1Create Box object b with size=5Calls __init__(5)b.size = 5
2Call print(b)Python calls b.__str__()Returns 'Box of size 5'
3print outputs stringOutputs to screenBox of size 5
4Program continuesNo more codeEnds
💡 No more code to run, program ends
Variable Tracker
VariableStartAfter 1After 2Final
b.sizeundefined555
Key Moments - 2 Insights
Why does print(b) show 'Box of size 5' instead of a default object address?
Because print calls the __str__ magic method (see execution_table step 2), which returns the custom string.
What happens if __str__ is not defined?
Python uses a default method that shows the object's type and memory address instead of a friendly string.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does step 2 do?
ACalls the __init__ method to create the object
BPrints the object directly without conversion
CCalls the __str__ magic method to get a string
DEnds the program
💡 Hint
See execution_table row 2 where print calls b.__str__()
At which step is the object's size set to 5?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Check variable_tracker after step 1 where b.size becomes 5
If __str__ was missing, what would print(b) show?
AA default object address string
BAn error message
CBox of size 5
DNothing
💡 Hint
Refer to key_moments explanation about default behavior without __str__
Concept Snapshot
Magic methods are special functions with double underscores like __str__.
They let Python objects respond to built-in operations.
For example, __str__ controls what print(object) shows.
If you define them, you customize object behavior.
If not, Python uses default actions.
Full Transcript
Magic methods in Python are special functions with names surrounded by double underscores, like __str__ or __init__. They let objects respond to built-in operations such as printing or adding. When you create an object and use print on it, Python looks for the __str__ method to get a string to show. If __str__ is defined, it returns a friendly string. If not, Python shows a default message with the object's type and memory address. This example creates a Box object with size 5. When print(b) runs, Python calls b.__str__() and prints 'Box of size 5'. This shows how magic methods customize object behavior in Python.