Add Your Heading Text Here

Table Of Contents:

  1. What Is A Magic Function?
  2. Examples Of Magic Methods.
  3. Know The Magic Methods Inside The Class.

(1) What Is A Magic Function?

  • Magic methods in Python are the special methods that start and end with double underscores( __ ).
  • They are also called dunder methods because they use double underscores(__).
  • Magic methods are not designed to be invoked by the user, but the invocation happens internally from the class on a specific action.
  • For example, when you initialize a class the __init__ method will be called automatically.
  • Here __init__ method is called a magic method because it is hiddenly called by the compiler itself.

(2) Examples Of Magic Function?

Example-1

class Student:
    def __init__(self,name,rollno):
        self.name = name
        self.rollno = rollno
    def details(self):
        print('Student Name:',self.name)
        print('Student Roll No:',self.rollno)
obj = Student('Abhispa',34)
obj.details()
Output:
Student Name: Abhispa
Student Roll No: 34

Note:

  • Here you can notice that I have not called the __init__ method, but it’s been automatically called.
  • So this is the magic of the Magic Method.

Example-2

class addition:
    def __add__(self,number):
        return 5 + number
obj = addition()
print(obj + 10)
Output:
15

Note:

  • Here you can notice that I have not called the __add__ method, but it’s been automatically called.
  • So this is the magic of the Magic Method.

Example-3

class Bikes:
    def __new__(self,name):
        print('I Have A New Bike.')
        inst = object.__new__(self)
        return inst
        
    def __init__(self,name):
        self.name = name
        print(f'I Have A {self.name} Bike.')
obj = Bikes('Ninja')
Output:
I Have A New Bike.
I Have A Ninja Bike.

Note:

  • Here you can notice that the __new__ method is first called and then the __init__ method.
  • Here __new__ and __init__ methods are the magic method.
    So this is the magic of the Magic Method.

(3) Know The Magic Methods Inside The Class.

  • The inbuilt dir( ) method is used to know the number of magic methods inherited by a class.
  • You need to pass the class name to the dir( ) method to get the list of magic methods.

Example-1

dir(str)
Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal',
'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 
'removesuffix','replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Example-2

dir(int)
Output:
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__',
'__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__',
'__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__',
'__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', 
'__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', 
'__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__',
'__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',
'__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
'__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',
'__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio',
'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

Leave a Reply

Your email address will not be published. Required fields are marked *