Welcome to our deep dive into Python's Magic Methods, also known as Dunder Methods! These methods are special functions in Python that have a double underscore __ before and after their names. They let you create custom behavior for your objects, making them a powerful tool in object-oriented programming. Let's get started! 📝
Dunder methods are called implicitly by Python when certain operations are performed on an object. They allow you to customize how your classes respond to these operations. Let's break it down:
__ is a special prefix for these methods, making them identifiable.Here are some of the basic dunder methods you'll come across:
__init__This is the constructor method that initializes the object. It is called when an object is created.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person('John', 25)
print(person.name) # Output: John__str__This method is used when we want to print the object. It returns a string representation of the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'Person: {self.name}, Age: {self.age}'
person = Person('John', 25)
print(person) # Output: Person: John, Age: 25__repr__This method is similar to __str__, but it is used for getting the object's printable representation when it is used in the context of a code. For example, in an interactive shell or in the print() function.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'Person({self.name!r}, {self.age})'
person = Person('John', 25)
print(person) # Output: Person('John', 25)What does the `__init__` method do in Python?
Here are some advanced dunder methods that will help you create more complex and flexible objects:
__getattr__ and __setattr__These methods allow you to customize the way attributes are accessed and modified for your objects.
class Person:
def __init__(self, name):
self.name = name
def __getattr__(self, attr):
if attr == 'age':
return 25
raise AttributeError(f"'Person' object has no attribute '{attr}'")
def __setattr__(self, key, value):
print(f'Setting attribute {key} to {value}')
super().__setattr__(key, value)
person = Person('John')
print(person.age) # Output: 25
person.age = 30
print(person.age) # Output: 30__call__This method allows your object to be called as a function.
class Adder:
def __init__(self):
self.total = 0
def __call__(self, *numbers):
self.total += sum(numbers)
return self.total
adder = Adder()
print(adder(1, 2, 3)) # Output: 6
print(adder(4, 5)) # Output: 10What does the `__getattr__` method do in Python?
Dunder methods are a powerful tool in Python, allowing you to customize the behavior of your classes and objects. By understanding and using them, you can create more flexible and reusable code. Keep experimenting, and happy coding! 💻💼