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.
Following is our simple Student
class:
A Basic Student Class
A very basic class, which takes three parameters to define a student — name
, phone_number
and standard
.
There are numerous magic methods available in python, we will see some basic and most widely used of those, to implement following scenarios:
**_length_**
_ function on one object?_**_obj[0]_**
?#python #oop-concepts