The very first thing one must learn and believe without a shred of doubt is that In python, everything is an object.

Python offers a host of magic methods (alternatively called dunder methods because of the “double underscores”) to make custom objects more intuitive, easy to use and **pythonic. **Let’s start with a very basic scenario:

string_sum_output = 'hello' + ' world' + '!'
integer_sum_output = 10 + 20
print(string_sum_output)
print(integer_sum_output)
o/p1:>> hello world!
o/p2:>> 30

At first glance o/p1 and o/p2 seems super normal. But let me ask you this,

how does python decide when to do arithmetic sum and when to concatenate values****if ‘+’ operator is used?

Most obvious answer will be based on data-types, which is not incorrect, but doesn’t reveal the real process of deciding though. That’s where magic methods come into picture. Certain behaviours of an objects can be controled and dictated by using these, so called, magic methods.

So in this article, we will see how to add certain behavioural traits to our custom classes, so that objects of those classes will have some special functionalities.


Student Class

Following is our simple Student class:

A Basic Student Class

A very basic class, which takes three parameters to define a student — namephone_number and standard.


Scenarios

There are numerous magic methods available in python, we will see some basic and most widely used of those, to implement following scenarios:

  1. What will be shown, when I print an object?
  2. How can I compare between two objects?
  3. _What will be returned if I apply built-in _**_length_**_ function on one object?_
  4. How to make the object iterable/iterator?
  5. _How to support indexing on the object, i.e. _**_obj[0]_**?
  6. And finally, what will be the result if any arithmetic operator (‘+’, ‘-’, ‘*’ etc) is used with the objects?

#python #oop-concepts

Make Python Objects Magical
2.60 GEEK