Python

Python Dunder Methods

Dunder methods are also called special techniques that are a set of predefined methods in Python that can be used to improve your classes. Because they begin and conclude with double underscores, such as __init__ or __str__, they are easily identifiable. In Python, these “dunders” or “special methods” are sometimes known as “magic methods.” However, adopting this phrase can make things appear more sophisticated than they are. These techniques should be handled as if they have built-in language aspects.

Dunder methods are extremely strong Python intrinsic methods that can be used to develop complex classes. This lesson provides a step-by-step guide of Python methods and how to use them, complete with examples. The consistency of Python’s popularity can be traced to the language’s popularity. For intrinsic methods like abs(), len(), sorted(), and many others, Python allows you to implement your custom objects. All you have to do now is add some unique methods to your class (dunder methods).

In this article, we have used phrases like dunder methods, magic methods, and special techniques, all of which fall into the same category. Before we go into the tutorial, you should be aware of something. Python programmers who are experienced with object-oriented programming (OOP) will recognize the __init__ method. The dunder method was named after the double underscores, which are known as dunder in Python. Because there are magic methods in Ruby that fulfill the same purpose, some Python programmers refer to them as such in Python. We usually refer to them as Special Methods because that’s what the Python manual calls them. Resultantly, if you see these methods in Python, assume they are Special Methods.

Example 1:

Similar to constructors in other programming languages, when an instance of a class is formed, the __init__ function for initialization is invoked without any call. In Python classes, “__init__” is a reserved method. In object-oriented terminology, it is referred to as a function Object() { [native code] }. This method is invoked when an object is formed from a class to permit the class to populate its properties. We can use the ‘+’ operator to combine two strings without needing to apply explicit typecasting because of these methods. Here is a detailed example of how to perform this. We declared our string class first, followed by the magic function to create an object. The object creation is completed after the driver code, and the object location is reported out at the end.

https://lh6.googleusercontent.com/W2GogWgs9cd7htwyETzMRJq-L1AzFn_GWKmXYo75RCcTqBuNRmV3Ht1W4XVYIsYjhKiHOk8VtORqYy-swPjoVQES3kP75U64Sou_a3R8IOoE2Zp_fK5zieA8QMH022B_xJMZdBnO

The code lines above merely print the string object’s memory address.

https://lh6.googleusercontent.com/T7lIkhezrz149eNN-1XHC42koeBDInjs9TMyc5rRWq_oJjUgaAQUXpMxNjOamC3vKoJ60Oks8uGzrXq_lldk8muYE8RqUpvRZNH-wnfj1-K5DcZk2WrlUYHlPxfIds13GQogkrRy

Example 2:

We’ll utilize the __repr__ method to represent our object in the following example.  The magic method __repr__ represents a class instance in a string. When we try to print a class object, the __repr__ function is called, which yields a string. By default, repr() returns the string representation of the value supplied to the eval function. By default, the custom class object provides a string in angle brackets containing the object’s name and address. Except for the addition of the __repr__ method after we’ve used the magic method to initialize the object, the code is the same as before.

https://lh6.googleusercontent.com/nX38L_A-oA7t47lUC8Hj5y4SEMkP9zh9yqq1Ldi1lAGGZ2QM7v-mZ0H_f8ke2P5alK3RTMnh9SKIaeGLiS2evgL6C3uyXlmUbqKpVesr1CHspWfdifSTTymeWEHNiK3YEqdrq0KM

Here you can see that the above have successfully displayed the string.

https://lh3.googleusercontent.com/6YWsdvwQ_uZGlm-QHgt6gC_fGp7o19L2xem6vYw_-QNsbNrQta5M6RrvMgtTeKGBtsMqvPoA-o9txrLeDupO065EtzjgGIikgixSRGRYTIiRoIIQm6ZzL1yhvKaFiZza5L8mN0SJ

Example 3:

We’ll now add the __add__ function to the String class. The class instance’s attributes are added using the __add__ magic method. Let’s pretend that object1 belongs to class A and object2 to class B and that both of these classes have an attribute named ‘a’ that contains an integer. After the operation object1 + object2 is done, the __add__ function implicitly adds the attributes of these objects, such as object1.a + object2.a. We re-initialized the string class in the code, as you can see in the first line of code. After that, we utilized the magic way to get the object started. The string object was then printed using the __add__ method. The object is created after the driver code, which is the next line of code. In the last line of code, we concatenated a String object with a string.

class String:

https://lh4.googleusercontent.com/M5UbFG8gybiWpehuPA8RJV5ysTmy3HjN4VDueBsHPzZ1hdIUF6gFISEEHHRk1TXpeGgTO6RqA3VWncmBtQnm5syRXoSCnhP4clvodHc7XuNep3kWPK1yTEdgzDB-4ExCc6uayVnB

Below is the output of the above-written code.

https://lh3.googleusercontent.com/pBKojG7KY9xuGKkqyNujZG78geISxMQfg72eYJYX_O8Gxj3PdwWFWFVH-oRmd7vbpuvqjdXl-r_UrCTWAFfbms3sEkn4O5kCFL19cOVncMfFcklPg3oyURVAMRgok83_NvrEBWB9

Conclusion:

Magic methods are Python methods with double underscores at the beginning and conclusion. Dunder methods or techniques are another name for them. Magic methods are not intended to be called directly by the user; instead, they are called internally by the class in reaction to a specific action. The __add__() method is called internally when you use the + operator to add two numbers, for example. Python’s built-in classes define a lot of magic methods. To find out how many magic methods a class has inherited, you can use the dir() function.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content

Page was generated in 0.070223093032837