Skip to main content

Magic Methods in Python

 




What Are Dunder Methods?

In Python, special methods are a set of predefined methods you can use to enrich your classes.

 They are easy to recognize because they start and end with double underscores, for example __init__ or __str__.




Dunder methods let you emulate the behavior of built-in types.

 For example, to get the length of a string you can call len('string'). But an empty class definition doesn’t support this behavior out of the box:

These “dunders” or “special methods” in Python are also sometimes called “magic methods.”


class NoLenSupport:
    pass

>>> obj = NoLenSupport()
>>> len(obj)
TypeError: "object of type 'NoLenSupport' has no len()"

To fix this, you can add a __len__ dunder method to your class:

class LenSupport:
    def __len__(self):
        return 42

>>> obj = LenSupport()
>>> len(obj)
42

Object Initialization: __init__


"__init__" is a reserved method in python classes. 

It is called as a constructor in object oriented terminology. 

This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.

class Hospital:
    """A simple Hospital class"""

    def __init__(self, doctor, salary):
        """
        This is the constructor that lets us create
        objects from this class
        """
        self.doctor = doctor
        self.salary = salary

Python __eq__

Introduction to the Python __eq__ method

By default, all Python objects inherit the __eq__ method from the base class object, which provides a basic equality comparison. This default behavior checks if two objects have the same identity, meaning they refer to the same memory location.

 

We will override the default method to implement a different use case


Suppose that you have the following Person class with three instance attributes: first_namelast_name, and age:

class Person: def __init__(self, first_name, last_name, age):    self.first_name = first_name     self.last_name = last_name      self.age = age
Code language: Python (python)

And you create two instances of the Person class:

ravi = Person('Ravi', 'shankar', 25)hema = Person('hema', 'malini', 25)
Code language: Python (python)

In this example, the john and jane objects are not the same object. And you can check it using the is operator:

print(ravi is hema) # False
Code language: Python (python)

Also, when you compare john with jane using the equal operator (==), you’ll get the result of False:

print(ravi == hema) # False
Code language: Python (python)

Since john and jane have the same age, you want them to be equal. In other words, you want the following expression to return True:

ravi == hema

To do it, you can implement the __eq__ dunder method in the Person class.

Python automatically calls the __eq__ method of a class when you use the == operator to compare the instances of the class. By default, Python uses the is operator if you don’t provide a specific implementation for the __eq__ method.

The following shows how to implement the __eq__ method in the Person class that returns True if two person objects have the same age:

class Person: def __init__(self, first_name, last_name, age):    self.first_name = first_name      self.last_name = last_name     self.age = age     def __eq__(self, other):         return self.age == other.age
Code language: Python (python)

Now, if you compare two instances of the Person class with the same age, it returns True:

ravi = Person('Ravi', 'shankar', 25) hema = Person('hema', 'malini', 25)print(ravi == hema) # True
Code language: Python (python)

And if two instances of the Person class don’t have the same age, the == operator returns False:

john = Person('John', 'Doe', 25) mary = Person('Mary', 'Doe', 27) print(john == mary) # False

Code language: Python (python)ws

__del__ 

The default behavior of the __del__ method inherited from object is to do nothing special when an object is deleted. It's essentially a no-op (no operation). Python's garbage collector automatically reclaims memory used by objects when they are no longer referenced, and the __del__ method is not typically needed for basic memory management.

 This is used to delete an instance and we cannot perform any operations related to that instance after that.

class Student:
def__init__(self,name,age):
self.name = name
self.age = age
def__del__(self):
print('Instance is deleted')
stud1=Student('tom',12)
del stud1
print(stud1.name)
Instance is deleted
NameError: name 'stud1' is not defined --> raising an error.
__lt__ in python:class student: def __init__(self,name,age): self.name=name self.age=age def __lt__(self,other): return self.age<other.age ajay=student("Ajay",32) vinith=student("Arun",12) print(ajay<vinith)#Output Falsethe __lt__ function in above compares the age of two students.
__gt__ in python:class student:
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __gt__(self,other):
        return self.age>other.age

ajay=student("Ajay",32)
vinith=student("Arun",12)

print(ajay>vinith)#Output Truethe __gt__ function in above compares the age of two students.

Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand these concepts with an example of Car class. # Has-A relationship --> By Composition class  Engine:    def   __init__ ( self ):      s

Architechture of Kubernetes

  Kubernetes Architecture and Components: It follows the client-server architecture, from a high level, a Kubernetes environment consists of a  control plane (master) , a  distributed storage system  for keeping the cluster state consistent ( etcd ), and a number of  cluster nodes (Kubelets). We will now explore the individual components of a standard Kubernetes cluster to understand the process in greater detail. What is Master Node in Kubernetes Architecture? The Kubernetes Master (Master Node) receives input from a CLI (Command-Line Interface) or UI (User Interface) via an API. These are the commands you provide to Kubernetes. You define pods, replica sets, and services that you want Kubernetes to maintain. For example, which container image to use, which ports to expose, and how many pod replicas to run. You also provide the parameters of the desired state for the application(s) running in that cluster. API Server: The  API Server  is the front-end of the control plane and the only