Dunder

2 beste casinoer 2020:
  • CASINO-X
    CASINO-X

    Enorme bonuser og jackpotter!

  • JOY CASINO
    JOY CASINO

    2 plass i rangeringen!

Python Dunder (Special, Magic) Methods List with Tutorial

There is a reason for Python’s popularity, it is the consistency of this language. Python allows you to support your custom objects for inbuilt functions like len() , abs() , sorted() and many others. You just need to implement some special methods (dunder methods) to your class.

In this tutorial I have used words like dunder methods, special methods and magic methods, all have the same meaning.

Before diving deep into the tutorial I want to share a fun fact about these names.

If you know object-oriented programming in Python then you will be familiar to this __init__ method. These have name dunder method because those __ double underscores are called dunder in Python.

There are magic methods in Ruby which serve the same purpose that’s why some Python developers use this name in Python language.

Mostly I call them Special Methods because this is what we see in Python documentation.

That is the reason if you see dunder methods or Magic Methods always assume them as Special Methods in Python.

2 beste casinoer 2020:
  • CASINO-X
    CASINO-X

    Enorme bonuser og jackpotter!

  • JOY CASINO
    JOY CASINO

    2 plass i rangeringen!

What are Special methods in Python?

The Special methods have a predefined syntax which is available to implement in our class.

The core data structures also implement these Special methods internally which allow them to be compatible with many inbuilt functions.

To understand this better, here is an example of a Python list. We can easily use len() function to find the length of any list but here is an alternative to confuse you.

Here __len__ is the magic method that does all the magic. Both syntaxes is the same for Python.

Whenever we use an inbuilt function, it tries to find a predefined method that does the task, like len() function finds __len__ method in that object.

The reason behind this was to build a common API which other classes can implement to do the same task. This removes the burden to learn methods of each class to do that task.

This is the reason I love Python. I remember the Java days of my coding when I spent most of my time thinking what is the method name to do any specific task. It was really frustrating.

Now I can think that you have a basic understanding of Special methods in Python.

List of all Special Methods in Python

There are very different types of Special methods and they are in large number. It is not possible to explain them all in a single post.

Here are the most popular and widely used list of Special or dunder methods in Python.

Basic Customizations

  • __new__(self) return a new object (an instance of that class). It is called before __init__ method.
  • __init__(self) is called when the object is initialized. It is the constructor of a class.
  • __del__(self) for del() function. Called when the object is to be destroyed. Can be used to commit unsaved data or close connections.
  • __repr__(self) for repr() function. It returns a string to print the object. Intended for developers to debug. Must be implemented in any class.
  • __str__(self) for str() function. Return a string to print the object. Intended for users to see a pretty and useful output. If not implemented, __repr__ will be used as a fallback.
  • __bytes__(self) for bytes() function. Return a byte object which is the byte string representation of the object.
  • __format__(self) for format() function. Evaluate formatted string literals like % for percentage format and ‘b’ for binary.
  • __lt__(self, anotherObj) for __le__(self, anotherObj) for __eq__(self, anotherObj) for == operator.
  • __ne__(self, anotherObj) for != operator.
  • __gt__(self, anotherObj) for > operator.
  • __ge__(self, anotherObj) for >= operator.

Arithmetic Operators

  • __add__(self, anotherObj) for + operator.
  • __sub__(self, anotherObj) for – operation on object.
  • __mul__(self, anotherObj) for * operation on object.
  • __matmul__(self, anotherObj) for @ operator (numpy matrix multiplication).
  • __truediv__(self, anotherObj) for simple / division operation on object.
  • __floordiv__(self, anotherObj) for // floor division operation on object.

Type Conversion

  • __abs__(self) make support for abs() function. Return absolute value.
  • __int__(self) support for int() function. Returns the integer value of the object.
  • __float__(self) for float() function support. Returns float equivalent of the object.
  • __complex__(self) for complex() function support. Return complex value representation of the object.
  • __round__(self, nDigits) for round() function. Round off float type to 2 digits and return it.
  • __trunc__(self) for trunc() function of math module. Returns the real value of the object.
  • __ceil__(self) for ceil() function of math module. The ceil function Return ceiling value of the object.
  • __floor__(self) for floor() function of math module. Return floor value of the object.

Emulating Container Types

  • __len__(self) for len() function. Returns the total number in any container.
  • __getitem__(self, key) to support indexing. LIke container[index] calls container.__getitem(key) explicitly.
  • __setitem__(self, key, value) makes item mutable (items can be changed by index), like container[index] = otherElement .
  • __delitem__(self, key) for del() function. Delete the value at the index key .
  • __iter__(self) returns an iterator when required that iterates all values in the container.

Here is a practical use case of __init__ special method in Python.

How to use Dunder or Special Magic Methods?

Now you know what are dunder methods in Python. It is very easy to use them in your custom created classes. They will extend the functionality of the class by making them compatible with inbuilt python function.

Note that it is not necessary and sometimes not possible to implement each and every Special method in any class. For example, you cannot divide two bank account together so there is no need to implement __truediv__ Special method in Account class.

Here is an example that explains the use of all Special methods mentioned above.

The Output of the above code is:

The only thing that is annoying in the output is the message Account Deleted. We don’t call del() function on the object still it executes.

This is the intelligence of Python. It deletes the objects as soon as the interpreter exits. The __del__() is executed implicitly.

Why use Dunder methods?

I have already leaked the main reason to implement dunder methods in your class. There are hundreds of Special methods available to implement in Python.

They give the ability to create classes that behave like native data structures like lists, tuples, dictionary, set etc.

The special methods provide a common API that allows developers to create interactive classes which are very useful. The benefit of special methods in Python is that we do not need to remember individual methods of any object to do any task.

For example how to calculate the length of an array in Java? Is it .len() method or .length() method?

Python is consistent in its design. The len() function works with the list, dictionary, tuples and other inbuilt data structures and you can also make your own object compatible with by implementing suitable dunder method (__len__() in this case).

In simple words, we can say that Dunder or Magic Methods make Python Consistent making it easy to learn and use.

Conclusion

Now, you have a complete understanding of dunder methods in Python. They are very useful to make our class interactive.

To have a better understanding of this you need to implement this on your own. There are certain things which you will learn only when you write code.

Here is the summary of the points.

  • Dunder Methods, Special Methods and Magic methods are the same thing in Python.
  • Dunder Methods makes our class compatible with inbuilt functions like abs() , len() , str() and many more.
  • Users don’t need to remember each and every method to do a certain task, just use inbuilt function and pass the object with required parameters.
  • They make Python consistent with its syntax.

dunder

To save this word, you’ll need to log in.

Definition of dunder

Definition of dunder (Entry 2 of 2)

Love words?

You must — there are over 200,000 words in our free online dictionary, but you are looking for one that’s only in the Merriam-Webster Unabridged Dictionary.

Start your free trial today and get unlimited access to America’s largest dictionary, with:

  • More than 250,000 words that aren’t in our free dictionary
  • Expanded definitions, etymologies, and usage notes
  • Advanced search features
  • Ad free!

History and Etymology for dunder

perhaps from Dutch donderen to thunder

2 beste casinoer 2020:
  • CASINO-X
    CASINO-X

    Enorme bonuser og jackpotter!

  • JOY CASINO
    JOY CASINO

    2 plass i rangeringen!

Anmeldelser av kasinoer og spilleautomater
Legg att eit svar

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: