The Wayback Machine - https://web.archive.org/web/20241122152541/https://www.geeksforgeeks.org/dunder-magic-methods-python/
Open In App

Dunder or magic methods in Python

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python Magic methods are the methods starting and ending with double underscores ‘__’. They are defined by built-in classes in Python and commonly used for operator overloading. 

They are also called Dunder methods, Dunder here means “Double Under (Underscores)”.

Python Magic Methods

Built in classes define many magic methods, dir() function can show you magic methods inherited by a class.

Example:

This code displays the magic methods inherited by int class.

Python
# code
print(dir(int))

Output
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '_...

Or, you can try cmd/terminal to get the list of magic functions in Python, open cmd or terminal, type python3 to go to the Python console, and type:

>>> dir(int)

Output:

 Magic methods in Python

Python Magic Methods

Below are the lists of Python magic methods and their uses.

Initialization and Construction

  • __new__: To get called in an object’s instantiation.
  • __init__: To get called by the __new__ method.
  • __del__: It is the destructor.

Numeric magic methods

  • __trunc__(self): Implements behavior for math.trunc()
  • __ceil__(self): Implements behavior for math.ceil()
  • __floor__(self): Implements behavior for math.floor()
  • __round__(self,n): Implements behavior for the built-in round()
  • __invert__(self): Implements behavior for inversion using the ~ operator.
  • __abs__(self): Implements behavior for the built-in abs()
  • __neg__(self): Implements behavior for negation
  • __pos__(self): Implements behavior for unary positive 

Arithmetic operators

  • __add__(self, other): Implements behavior for the + operator (addition).
  • __sub__(self, other): Implements behavior for the – operator (subtraction).
  • __mul__(self, other): Implements behavior for the * operator (multiplication).
  • __floordiv__(self, other): Implements behavior for the // operator (floor division).
  • __truediv__(self, other): Implements behavior for the / operator (true division).
  • __mod__(self, other): Implements behavior for the % operator (modulus).
  • __divmod__(self, other): Implements behavior for the divmod() function.
  • __pow__(self, other): Implements behavior for the ** operator (exponentiation).
  • __lshift__(self, other): Implements behavior for the << operator (left bitwise shift).
  • __rshift__(self, other): Implements behavior for the >> operator (right bitwise shift).
  • __and__(self, other): Implements behavior for the & operator (bitwise and).
  • __or__(self, other): Implements behavior for the | operator (bitwise or).
  • __xor__(self, other): Implements behavior for the ^ operator (bitwise xor).
  • __invert__(self): Implements behavior for bitwise NOT using the ~ operator.
  • __neg__(self): Implements behavior for negation using the – operator.
  • __pos__(self): Implements behavior for unary positive using the + operator.

String Magic Methods

  • __str__(self): Defines behavior for when str() is called on an instance of your class.
  • __repr__(self): To get called by built-int repr() method to return a machine readable representation of a type.
  • __unicode__(self): This method to return an unicode string of a type.
  • __format__(self, formatstr): return a new style of string.
  • __hash__(self): It has to return an integer, and its result is used for quick key comparison in dictionaries.
  • __nonzero__(self): Defines behavior for when bool() is called on an instance of your class. 
  • __dir__(self): This method to return a list of attributes of a class.
  • __sizeof__(self): It return the size of the object.

Comparison magic methods

  • __eq__(self, other): Defines behavior for the equality operator, ==.
  • __ne__(self, other): Defines behavior for the inequality operator, !=.
  • __lt__(self, other): Defines behavior for the less-than operator, <.
  • __gt__(self, other): Defines behavior for the greater-than operator, >.
  • __le__(self, other): Defines behavior for the less-than-or-equal-to operator, <=.
  • __ge__(self, other): Defines behavior for the greater-than-or-equal-to operator, >=.

Dunder or Magic Methods in Python

Let’s see some of the Python magic methods with examples:

1. __init__ method

The __init__ method for initialization is invoked without any call, when an instance of a class is created, like constructors in certain other programming languages such as C++, Java, C#, PHP, etc.

These methods are the reason we can add two strings with the ‘+’ operator without any explicit typecasting. 

Python
# declare our own string class
class String:
    
    # magic method to initiate object
    def __init__(self, string):
        self.string = string
        
# Driver Code
if __name__ == '__main__':
    
    # object creation
    string1 = String('Hello')

    # print object location
    print(string1)

Output
<__main__.String object at 0x7f538c059050>

2. __repr__ method

__repr__ method in Python defines how an object is presented as a string.

The below snippet of code prints only the memory address of the string object. Let’s add a __repr__ method to represent our object. 

Python
# declare our own string class
class String:
    
    # magic method to initiate object
    def __init__(self, string):
        self.string = string
        
    # print our string object
    def __repr__(self):
        return 'Object: {}'.format(self.string)

# Driver Code
if __name__ == '__main__':
    
    # object creation
    string1 = String('Hello')

    # print object location
    print(string1)

Output
Object: Hello

If we try to add a string to it:

Python
# declare our own string class
class String:
    
    # magic method to initiate object
    def __init__(self, string):
        self.string = string
        
    # print our string object
    def __repr__(self):
        return 'Object: {}'.format(self.string)

# Driver Code
if __name__ == '__main__':
    
    # object creation
    string1 = String('Hello')
    
    # concatenate String object and a string
    print(string1 +' world')

Output:

TypeError: unsupported operand type(s) for +: 'String' and 'str'

3. __add__ method

__add__ method in Python defines how the objects of a class will be added together. It is also known as overloaded addition operator.

Now add __add__ method to String class : 

Python
# declare our own string class
class String:
    
    # magic method to initiate object
    def __init__(self, string):
        self.string = string 
        
    # print our string object
    def __repr__(self):
        return 'Object: {}'.format(self.string)
        
    def __add__(self, other):
        return self.string + other

# Driver Code
if __name__ == '__main__':
    
    # object creation
    string1 = String('Hello')
    
    # concatenate String object and a string
    print(string1 +' Geeks')

Output
Hello Geeks

We have discussed some of the Python magic methods or Dunder methods. Magic methods in Python can be used to different functionalities in your class.

Hope you learn about Python magic methods from this article, and use it in your projects.

Dunder or magic methods in Python – FAQs

What is a Dunder or Magic Method in Python?

In Python, a “dunder” or “magic” method is a method that has double underscores before and after its name. These methods are not meant to be invoked directly by you, but the interpretation of them gets invoked internally by the Python interpreter to perform specific actions. For example, when you add two numbers with the + operator, the __add__ method is invoked.

What is the Python Magic Method?

Magic methods in Python are special methods which have double underscores at the beginning and end of their names. They are also known as “special methods.” They are used to emulate the behavior of built-in types. For instance, __init__, __add__, __len__, __repr__, and many others are all magic methods. These methods enable us to use Python operators and built-in functions on our custom objects.

What is __le__ a Magic Method for?

The __le__ method in Python is a magic method used to define the behavior of the less than or equal to operator <=. It stands for “less than or equal to.” When you use the <= operator between two objects, Python internally calls the __le__ method.

Example:

class Number:
def __init__(self, value):
self.value = value

def __le__(self, other):
return self.value <= other.value

# Usage
n1 = Number(5)
n2 = Number(10)
print(n1 <= n2) # Output: True

What is a Dunder?

A “dunder” (short for double underscore) refers to the special methods in Python that are surrounded by double underscores (__method__). These methods are also known as magic methods. The term “dunder” is often used to highlight the special status these methods have in Python and their direct association with built-in Python behavior.

What is the __repr__ Magic Method in Python?

The __repr__ method in Python is a special magic method used to represent your object’s class instances as a string. The goal of __repr__ is to be unambiguous and, if possible, match the string needed to recreate the object being represented. It’s often used for debugging and development. It’s good practice to define __repr__ such that it returns a valid Python expression that could be used to recreate the object.

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})"

# Usage
p = Person("Alice", 30)
print(p) # Output: Person(name='Alice', age=30)

This implementation of __repr__ provides a clear and concise description of the object that can be useful during debugging and logging.



Previous Article
Next Article

Similar Reads

Customize your Python class with Magic or Dunder methods
The magic methods ensure a consistent data model that retains the inherited feature of the built-in class while providing customized class behavior. These methods can enrich the class design and can enhance the readability of the language. So, in this article, we will see how to make use of the magic methods, how it works, and the available magic m
13 min read
__closure__ magic function in Python
Almost everything in Python is an object, similarly function is an object too and all the function objects have a __closure__ attribute. __closure__ is a dunder/magic function i.e. methods having two underscores as prefix and suffix in the method name A closure is a function object that remembers values in enclosing scopes even if they are not pres
1 min read
Python - __lt__ magic method
Python __lt__ magic method is one magic method that is used to define or implement the functionality of the less than operator "<" , it returns a boolean value according to the condition i.e. it returns true if a<b where a and b are the objects of the class. Python __lt__ magic method Syntax Syntax: __lt__(self, obj) self: Reference of the ob
2 min read
Python __repr__() magic method
Python __repr__() is one of the magic methods that returns a printable representation of an object in Python that can be customized or predefined, i.e. we can also create the string representation of the object according to our needs. Python __repr__() magic method Syntax Syntax: object.__repr__() object: The object whose printable representation i
4 min read
Python __len__() magic method
Python __len__ is one of the various magic methods in Python programming language, it is basically used to implement the len() function in Python because whenever we call the len() function then internally __len__ magic method is called. It finally returns an integer value that is greater than or equal to zero as it represents the length of the obj
2 min read
Python __add__() magic method
Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator "+" in Python. Python __add__() Syntax Syntax: obj1.__add__(self, obj2) obj1: First object to add in the second object.obj2: Second object to add in the first object. Return
1 min read
Magic 8 Ball Program In Python
The Magic 8 Ball is a toy used for fortune-telling or seeking advice. In Python, we can recreate this by using a list of possible answers and selecting one randomly each time a user asks a question. This program is an excellent exercise for learning about lists, user input, and importing libraries in Python. Step to Implement 8 Ball Program In Pyth
5 min read
Magic Commands for Profiling in Jupyter Notebook
Jupyter Notebook is a versatile tool or IDE widely used mostly by data scientists, researchers, and programmers for interactive computing and data analysis, dashboards, and visualizations. It offers a unique and rich set of features. Some topics are there it can perform such as: running the code in different languages, timing the code execution, de
9 min read
Useful IPython magic commands
In this article, we will cover IPython Magic commands/functions and discuss various types of magic commands available. In this article we will be using Jupyter Notebook to execute the magic commands first, we look at what are Magic functions and why we use them, then different types of magic functions followed by examples. There are a lot of magic
6 min read
Jupyter Notebook - Cell Magic Functions
In this article, we will cover Cell Magic Functions in Jupyter Notebook we will discuss various functions. But first, we look at what Jupyter Notebook and Cell Magic functions and why we use them. There are a lot of cell magic functions but in this article, we discuss the most commonly used cell magic functions. Jupyter NotebookThe Jupyter Notebook
5 min read
Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase & title)
Some of the string basics have been covered in the below articles Strings Part-1 Strings Part-2 The important string methods will be discussed in this article1. find("string", beg, end) :- This function is used to find the position of the substring within a string.It takes 3 arguments, substring , starting index( by default 0) and ending index( by
4 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Accessing Attributes and Methods in Python
Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() - This function is used to access the attribute of object. hasattr() - This function is us
3 min read
Python | Float type and its methods
The float type in Python represents the floating point number. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers. Python float values are represented as 64-bit double-precision values. The maximum value any fl
3 min read
Bound, unbound, and static methods in Python
Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in detail below. Bound methods If a function is an attr
5 min read
Http Request methods - Python requests
Python requests module has several built-in methods to make Http requests to specified URI using GET, POST, PUT, PATCH or HEAD requests. A Http request is meant to either retrieve data from a specified URI or to push data to a server. It works as a request-response protocol between a client and server. A web browser may be the client, and an applic
7 min read
Response Methods - Python requests
When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being - get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the
5 min read
Accessor and Mutator methods in Python
In Python, class is a prototype for objects which is a user-defined type. It specifies and defines objects of the same type, a class includes a cluster of data and method definitions. Moreover, an object is a single instance of a class but you can create many objects from a single class.Note: For more information, refer to Python Classes and Object
3 min read
10 Python File System Methods You Should Know
While programming in any language, interaction between the programs and the operating system (Windows, Linux, macOS) can become important at some point in any developer's life. This interaction may include moving files from one location to another, creating a new file, deleting a file, etc. In this article, we will discuss 10 essential file system
6 min read
Element methods in Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Selenium in Python works with elements. An element can be a tag, property, or anything, it is an instance of class selenium.webdriver.remote.webelement.WebElement. After you find an element on screen using selenium, you might want to click it or find sub-elements, etc. Sele
3 min read
Web Driver Methods in Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What
5 min read
Methods of Ordered Dictionary in Python
An OrderedDict is a dict that remembers the order in that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. Ordered dictionary somehow can be used in the place where there is a use of hash Map and queue. It has chara
3 min read
Subclass and methods of Shelve class in Python
Shelve is a module in Python's standard library which can be used as a non-relational database. The key difference between a dbm and shelve is that shelve can serve its values as any arbitrary object which can be handled by pickle module while in dbm database we can only have standard datatypes of Python as its database values. The key in shelve is
4 min read
Advanced Python List Methods and Techniques
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creati
6 min read
Ensemble Methods in Python
Ensemble means a group of elements viewed as a whole rather than individually. An Ensemble method creates multiple models and combines them to solve it. Ensemble methods help to improve the robustness/generalizability of the model. In this article, we will discuss some methods with their implementation in Python. For this, we choose a dataset from
11 min read
Python Tuple Methods
Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples. Count() MethodThe count() method of Tuple returns the number of times the given element appears in the tuple. Syntax: tuple.count(
3 min read
Python Set Methods
A Set in Python is a collection of unique elements which are unordered and mutable. Python provides various functions to work with Set. In this article, we will see a list of all the functions provided by Python to deal with Sets. Adding and Removing elementsWe can add and remove elements form the set with the help of the below functions - add(): A
2 min read
Python Input Methods for Competitive Programming
Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. In online coding platforms, if the C/C++ limit provided is x. Usually, in Java time provided is 2x, and in Python, it's 5x. To improve the speed of code execution for input/output intensive problems, languages have
6 min read
Practice Tags :
three90RightbarBannerImg