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

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating

#7-1-619/A/3/B, Plot No 48, SAP street, Gayathri Nagar, Behind Maitrivanam, Hyderabad 500 038.

Subscribe Form

Thanks for submitting!

91 9693996999

Python Interview Questions | Python Interview Questions for freshers |  Python Coding Questions and Answers | python programming interview questions | python technical interview questions |  python interview questions and answers for experienced | python basic interview questions and answers | Python coding questions |  Top Python interview questions

  • Youtube
  • Facebook
  • Twitter
  • LinkedIn

©2023 by Learner Landmark. All Rights Reserved.

bottom of page