Learn Python – Python magic method- Basic and advance

Python magic approach is defined as the extraordinary approach which adds “magic” to a class. It starts offevolved and ends with double underscores, for example, _init_ or _str_.

The built-in training define many magic methods. The dir() characteristic can be used to see the range of magic techniques inherited with the aid of a class. It has two prefixes, and suffix underscores in the technique name.

It is most regularly used to define the overloaded behaviors of predefined operators.


The _init_ method is referred to as after the occasion of the classification has been created but earlier than it back to the caller. It is invoked besides any call, when an occasion of the class is created like constructors in other programming languages such as C++, Java, C#, PHP, etc. These strategies are additionally regarded as initialize and are known as after _new_. Its the place you should initialize the instance variables.


This feature computes “informal” or a properly printable string representation of an object and have to return a string object.


This feature is called through the repr() built-in feature to compute the “official” string representation of an object and returns a machine-readable illustration of a type. The intention of the _repr_ is to be unambiguous.


This function must return the size of an object.


We can make an object callable by adding the _call_ magic method, and it is any other approach that is now not wanted pretty as frequently is _call_.

If described in a class, then that category can be called. But if it was once a function, instance itself as a substitute than modifying.


Just as _init_, which is a constructor method, _del_ is like a destructor. If you have opened a file in _init _, then _del_ can shut it.


It provides to compute a byte-string illustration of an object and ought to return a string object.


This method gets invoked when >= operator is used and returns True or False.


This function gets called for the unary operator.


This function receives referred to as on the exponents with arguments. e.g. a**=b.


This characteristic receives known as on contrast the use of <= operator.


This feature returns the Boolean price of the object. It gets invoked when the bool (self) function is called.