25. Python's __magic__ Methods
Here Python code snippets that showcase the use of Python's dunder methods (a.k.a. magic methods) like __init__, __str__, __repr__, and others, to customize class behavior.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.name) # Alice
print(p.age) # 30class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old."
p = Person("Alice", 30)
print(p) # Alice is 30 years old.Last updated