Python Magic Methods: Adding “Magic” to Your Classes

Python Magic Methods

Magic methods in Python are special methods surrounded by double underscores (e.g., __init__, __str__) that allow you to integrate Python’s built-in functionalities into your custom classes. These methods enable you to perform specific operations and enhance the structure and usability of your classes.


Key Python Magic Methods Explained

1. __init__ Method

The __init__ method, often called the constructor, initializes a class’s attributes when an instance is created. It is called automatically, just like constructors in languages such as C++, Java, or PHP.

Code Example:

# Python program to demonstrate the __init__ method

class Methods:
    def __init__(self, name, std, marks):
        print("The __init__ method has been called!")
        self.name = name
        self.std = std
        self.marks = marks

# Creating an instance of the class
student = Methods("Itika", 11, 98)
print(f"Name: {student.name}, Standard: {student.std}, Marks: {student.marks}")

Output:

The __init__ method has been called!
Name: Itika, Standard: 11, Marks: 98

Download New Real Time Projects :-Click here


2. __new__ Method

The __new__ method creates a new instance of a class before initializing it. It’s implicitly called before __init__ and can be used to customize object creation.

Code Example:

class Method:
    def __new__(cls):
        print("Creating an instance using __new__ method")
        return super().__new__(cls)

    def __init__(self):
        print("Initializing the instance with __init__ method")

# Creating an instance
Method()

Output:

Creating an instance using __new__ method
Initializing the instance with __init__ method

3. __add__ Method

The __add__ method allows you to define custom behavior for the + operator. It can be used to add attributes of class instances.

Code Example Without __add__:

class Method:
    def __init__(self, value):
        self.attribute = value

# Creating instances
instance_1 = Method("Attribute")
instance_2 = Method(" 27")

# Concatenating attributes
print(instance_1.attribute + instance_2.attribute)

Output:

Attribute 27

Code Example With __add__:

class Method:
    def __init__(self, value):
        self.attribute = value

    def __add__(self, other):
        return self.attribute + other.attribute

# Creating instances
instance_1 = Method("Attribute")
instance_2 = Method(" 27")

# Adding attributes
print(instance_1 + instance_2)

Output:

Attribute 27

PHP PROJECT:- CLICK HERE


4. __repr__ Method

The __repr__ method provides a string representation of an object, which is helpful for debugging and logging.

Code Example:

class Method:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def __repr__(self):
        return f"Method(x={self.x}, y={self.y}, z={self.z})"

# Creating an instance
instance = Method(4, 6, 2)
print(instance)

Output:

Method(x=4, y=6, z=2)

5. __contains__ Method

The __contains__ method is called when using the in keyword to check for membership.

Code Example:

class Method:
    def __init__(self, container):
        self.container = container

    def __contains__(self, item):
        return item in self.container

# Creating an instance
instance = Method([4, 6, 8, 9, 1])

# Checking for membership
print(4 in instance)  # True
print(5 in instance)  # False

Output:

True
False

6. __call__ Method

The __call__ method enables you to call an instance like a function.

Code Example:

class Method:
    def __init__(self, multiplier):
        self.multiplier = multiplier

    def __call__(self, value):
        return self.multiplier * value

# Creating an instance
instance = Method(7)
print(instance(5))  # Output: 35

7. __iter__ Method

The __iter__ method makes an object iterable, allowing it to be used in loops.

Code Example:

class Method:
    def __init__(self, start, stop):
        self.start = start
        self.stop = stop

    def __iter__(self):
        for num in range(self.start, self.stop + 1):
            yield num ** 2

# Iterating over an instance
for square in Method(3, 8):
    print(square)

Output:

9
16
25
36
49
64

  • python magic methods list
  • python magic methods documentation
  • python 3 magic methods
  • python dunder methods
  • magic methods in python w3schools
  • magic methods in python example
  • dunder methods in python w3schools
  • python magic methods comparison
  • Python Magic Methods
See also  Python Decorators: A Comprehensive Guide

Post Comment