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_name
, last_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
Post a Comment