Python Dunder or Magic Methods (With Examples)

PYTHON MAGIC METHOD:

In Python, magic methods (also known as dunder methods) are special methods that start and end with double underscores (e.g., .__init__’ ,’ __str__’,’ __add__’). These methods provide a way to define how objects of a class behave in various contexts, such as arithmetic operations, comparisons, string representations, and more.

Python Dunder or Magic Methods | diplomawaale.blogspot.com
Python Dunder


IT'S TYPES:

1. __init__(self, ...): This method is the constructor and is automatically called when an object is created. It initializes the object's attributes.

2. __str__(self): This method defines the string representation of an object. It's called by the built-in str() function and print().

3. __repr__(self): This method defines a more detailed and unambiguous string representation of an object. It's used by the built-in repr() function.

4. __len__(self): This method defines the behavior of the len() function when called on an object. It's commonly used for sequences (lists, strings, etc.).

5. __getitem__(self, key): This method allows you to define how indexing (obj[key]) works for objects of your class.

6. __setitem__(self, key, value): This method allows you to define how assignment to an index (obj[key] = value) works for objects of your class.

7. __delitem__(self, key): This method allows you to define how deletion of an index (del obj[key]) works for objects of your class.

8. __add__(self, other): This method defines the behavior of the + operator when used with objects of your class.

9. __sub__(self, other): This method defines the behavior of the - operator when used with objects of your class.

10. __eq__(self, other): This method defines the behavior of the equality (==) operator.

11. __lt__(self, other): This method defines the behavior of the less than (<) operator.

12. __gt__(self, other): This method defines the behavior of the greater than (>) operator.

13. __le__(self, other): This method defines the behavior of the less than or equal to (<=) operator.

14. __ge__(self, other): This method defines the behavior of the greater than or equal to (>=) operator.

15. __del__(self): This method is called when an object is about to be deleted. It can be used to perform cleanup operations.


THE  '__INIT__ ' FUNCTION:

The ‘__init__ ‘function is a special method in Python classes, often referred to as the constructor. It's automatically called when you create an instance of a class and is used to initialize the attributes (properties) of the object. The’ __init__ ‘method allows you to set up the initial state of the object by providing values for its attributes.

EXAMPLE:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Creating an instance of the Person class
person1 = Person("Alice", 30)

print(person1.name)  # Output: Alice
print(person1.age)   # Output: 30

THE '__STR__' FUNCTION:

The’ __str__’ function is a special method in Python classes that defines a human-readable string representation of an object. This method is automatically called when you use the built-in ‘str()’ function or the ‘print()’ function with an object of your class. It allows you to customize the textual representation of your objects in a way that is useful and informative.

EXAMPLE:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Person(name: {self.name}, age: {self.age})"

# Creating an instance of the Person class
person1 = Person("Alice", 30)

# Using the str() function
print(str(person1))  # Output: Person(name: Alice, age: 30)

# Using the print() function
print(person1)       # Output: Person(name: Alice, age: 30)

THE '__REPR__' FUNCTION:

The ‘__repr__’ function is a special method in Python classes that defines an unambiguous string representation of an object. This method is automatically called when you use the built-in ‘repr()’ function with an object of your class. It's commonly used for providing detailed debugging information about an object, which can be especially useful during development and testing.

EXAMPLE:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"

# Creating an instance of the Person class
person1 = Person("Alice", 30)

# Using the repr() function
print(repr(person1))  # Output: Person(name='Alice', age=30)

THE '__LEN__' FUNCTION:

The ‘__len__’ method is a special method in Python classes that allows you to define the behavior of the built-in ‘len()’ function when used with objects of your class. By implementing the ‘__len__’ method, you can customize how the length of your objects is determined.

EXAMPLE:

class MyContainer:
    def __init__(self, data):
        self.data = data

    def __len__(self):
        return len(self.data)

# Creating an instance of the MyContainer class
my_container = MyContainer([1, 2, 3, 4, 5])

# Using the len() function
length = len(my_container)
print(length)  # Output: 5

THE '__ITER__' FUNCTION:

The ‘__iter__’ method is a special method in Python classes that allows you to define how objects of your class should behave when used in iteration contexts, such as loops or when using the’ iter()‘function. By implementing the ‘__iter__’ method, you can create iterable objects that can be looped over using a for loop or used with other iteration-related functions.

EXAMPLE:

class MyIterable:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < len(self.data):
            value = self.data[self.index]
            self.index += 1
            return value
        else:
            raise StopIteration

# Creating an instance of the MyIterable class
my_iterable = MyIterable([1, 2, 3, 4, 5])

# Using a for loop to iterate over the object
for item in my_iterable:
    print(item)

# Using the iter() function and next() function
iter_obj = iter(my_iterable)
print(next(iter_obj))  # Output: 1
print(next(iter_obj))  # Output: 2
print(next(iter_obj))  # Output: 3

THE '__CALL__' FUNCTION:

In Python, the '__call__' method is a special method that you can define within a class. When you create an instance of a class and then call that instance as if it were a function, Python will internally invoke the '__call__' method of that instance. This allows you to make an object behave like a function.

EXAMPLE:

class Counter:
    def __init__(self):
        self.count = 0

    def __call__(self):
        self.count += 1
        return self.count

# Create an instance of Counter
counter = Counter()

# Call the instance to increment and get the count
print(counter())  # Output: 1
print(counter())  # Output: 2
print(counter())  # Output: 3

Post a Comment

0 Comments