Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
Python Magic Methods: Adding “Magic” to Your Classes - Python Magic Methods

Python Magic Methods: Adding “Magic” to Your Classes

Posted on November 21, 2024December 21, 2024 By Rishabh saini No Comments on 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.

Python Magic Methods
Python Magic Methods


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

Python Magic Methods
Python Magic Methods

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

Python Magic Methods
Python Magic Methods


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

Python Magic Methods
Python Magic Methods

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)

Python Magic Methods
Python Magic Methods


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

Python Magic Methods
Python Magic Methods


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

Python Magic Methods
Python Magic Methods


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
Python Magic Methods


  • 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

Post Views: 708
Python Tags:dunder methods, dunder methods in python, learn python, magic method, magic methods, magic methods in python, magic methods python, Python, python class dunder methods, python class methods, python classes, python dunder, python dunder methods, python dunder methods tutorial, python magic method, python magic methods, python methods, python oop, python programming, python special methods, Python Tutorial, special methods

Post navigation

Previous Post: Simple CRUD Functionality in PHP with Source Code
Next Post: The Future of Artificial Intelligence

More Related Articles

Connecting SQLite with Python: A Step-by-Step Guide - Connecting SQLite with Python Connecting SQLite with Python: A Step-by-Step Guide Python
Python Tkinter Frame Widget Python Tkinter Frame Widget Python
Python Multiprocessing: A Complete Guide - Screenshot 2024-11-29 200152 Python Multiprocessing: A Complete Guide Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

  1. Python High-Order Functions: A Comprehensive Guide
  2. Finding the Second Largest Number in Python
  3. Python Constructor: A Guide to Initializing Objects in Python
  4. Weather Information App
  5. Database Operations: UPDATE and DELETE in MySQL Using Python
  6. How to Install Django: Step-by-Step Guide

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,613)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,215)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,867)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme