Day 36 Of Documenting My Learning Journey
Source: Dev.to
What I Did Today
- Learnt dunder (magic) methods in Python.
Magic Methods / Dunder Methods
Python provides many special methods whose names start and end with double underscores (__).
You can view the full list by running:
print(dir(object))
Below are two commonly used dunder methods:
__init__
The __init__ method allows you to initialize an object’s attributes when it is created.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
__str__
The __str__ method defines the string representation of an object, which is returned by str(obj) and used by print.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
The advantage of dunder methods is that they are invoked automatically by Python, so you don’t need to call them explicitly.
Resources I Used
- Python Refresher Series by Bonaventure Ogeto (YouTube)
- GitHub for documenting and pushing to my public repository
What’s Next
- Continue with Python OOP Basics – Part 2.