top of page

Dunder or Special Methods in python

Updated: Feb 10, 2023

Dunder/Special methods are called by special syntax (such as arithmetical operations). This is the python approach for operator overloading.


for example:


	10 + 20 
	int.__add__(10, 20)

	text = "Hello" + "World"
	text = str.__add__("Hello", "World")

+ operator performs arithmetical addition with numeric types.

+ operator performs concatenation with string types.


Dunder/Special methods are used to customize the object creation in user defined class types.

object.__new__(cls)

It is called to create a new instance of class, and it's return value is the new instance.


object.__init__(self)

It is called after the instance has been created (by __new__()). Dunder new (), and init () methods are automatically called when you are creating an object.

  • __new__ creates a new instance

  • __init__ initializes the instance

print(emp1) statement looks for the implementation of __str__ or __repr__ in the class, otherwise it prints the reference of the object.


object.__repr__(self)

repr () meant for unambiguous representation of the object, which is used for logging or debugging the code by the developers. repr () should return a valid python expression that could be used to recreate an object with the same value.

print(emp1) calls repr(emp1), which returns a valid expression of python, that could be used to create instance.


object.__str__(self)

str() meant for readable representation of the object, which is readable format to the end user.

if you are not providing the dunder __str__, then __repr__ is the fallback method.


so, explicitly you can call dunder repr(), and str() methods to get desired results.

object.__del__(self)

Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor.

Here we created only one instance, but it has two references, emp1 and emp2. by calling del emp1, the count will become 1, while leaving the local scope count will become zero, then only it calls the destructor.


Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark
116 views0 comments

Recent Posts

See All
bottom of page