Introduction to Magic Methods in Python
If you’ve learnt Python for a while, chances are that you’ve come across the term magic method at some point. Simply put, magic methods belong in classes, has 2 underscore characters in front of and behind its name eg. __init__
, __str__
& __add__
, and are invoked when we perform certain actions in Python.
The __init__ Method
The __init__
method is invoked when we create an object from a class. Let’s say we have a Dog class:
class Dog:
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
Here, our __init__
function takes in 3 attributes name
, age
and breed
. This means that when we create a Dog object, we must pass in these 3 arguments.
rocky = Dog("rocky", 4, "german shepherd")
fifi = Dog("fifi", 5, "german shepherd")
baaron = Dog("baaron", 6, "german shepherd")
Here, each Dog object is created with 3 attributes — name, age and breed.
The __str__ Method
The __str__
method returns a string representation of the object, and is called when we convert an object into a string. If we didn’t have a __str__
method, we might get something like this if we print the object directly