Introduction
Python is a powerful programming language with a rich set of built-in functions and modules that allow developers to perform a wide range of tasks. Developers will be able to achieve very specific functions without writing complicated code. One category of functions is aptly named "special functions".
In this article, we will explore the concept of special functions in Python, what they are, how they work, and some examples of how they can be used.
What Are Special Functions in Python?
Special functions, also known as magic methods or dunder methods (short for double underscore methods), are a set of predefined functions that provide special behaviour to objects in Python. They are called special functions because they are invoked automatically in certain situations and provide special functionality that cannot be achieved through regular Python syntax.
Special functions are always preceded and followed by double underscores, for example __init__
, __str__
, __eq__
, and __add__
. These functions are used to define classes and their behaviour in Python, and they can be used to customize the behaviour of built-in Python objects such as strings, lists, and dictionaries.
How Do Special Functions Work?
Special functions are invoked automatically when certain events occur in Python, such as object creation, attribute access, and mathematical operations. When a special function is invoked, it is passed a reference to the object that it is being called on, as well as any additional arguments that are specified.
__init__( ) :
Initialization method
For example, the __init__()
special function is called automatically when a new object is created from a class. The self
parameter, which represents the object being created, is passed to __init__()
along with any other arguments that are specified when the object is instantiated.
Following is a simple class that defines a MyClass
object and uses the __init__()
special function to initialize the object's properties:
class MyClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def __str__(self):
return f"{self.arg1}, {self.arg2}!"
my_object = MyClass("Hello", 123)
print(my_object) # Hello, 123!
In the example above, the __init__()
special function takes two arguments, arg1
and arg2
, and sets the corresponding properties of the MyClass
object. The __str__()
special function is also defined here, which returns a string representation of the MyClass
object.
__str__( ) :
String representation of an object
The __str__()
special function is used to return a string representation of an object. It is called automatically when the print()
function is used on an object, or when the object is converted to a string using the str()
function. It is used to provide a human-readable representation of the object.
class User:
def __init__(self, name, num):
self.name = name
self.num = num
def __str__(self):
return f"{self.name} (Contact: {self.num})"
my_user = User("John", 5551234)
print(my_user) # prints "John (Contact: 5551234)"
__eq__( ) :
Object equality
The __eq__()
special function is used to define the equality operator (==
) for an object. It takes two arguments, the object being compared (self
) and the object being compared against (other
), and returns True
if they are equal and False
otherwise. By default, two objects are considered equal only if they are the same object in memory. However, we can define custom behavior for object equality using __eq__()
.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2) # prints True
In the example above, we define a Point
class with two attributes x
and y
. We define the __eq__()
method to compare two points for equality based on their x
and y
values. When we compare p1 == p2
, the __eq__()
function is called.
Now consider this. Here we define __eq__()
to compare two points but of reversed x
and y
positions.
class Reverse_point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.y and self.y == other.x
p1 = Reverse_point(1, 2)
p2 = Reverse_point(1, 2)
print(p1 == p2) # prints False
__lt__( )
and __gt__( ) : Object comparison
The __lt__()
and __gt__()
special functions are used to define the less-than (<
) and greater-than (>
) operators for an object. They take two arguments, the object being compared (self
) and the object being compared against (other
), and return True
__repr__( ) : Object representation
The __repr__()
function is a special function used to return a string representation of an object that can be used to recreate the object. This function is called when the repr()
function is called on an object. It is used to provide a technical representation of the object.
__len__( ) : Object length
The __len__()
function is a special function used to return the length of an object. This function is called when the len()
function is called on an object. It is used to provide the number of items in an object.
__getitem__() : Get item
The __getitem__()
function is a special function used to get an item from an object. This function is called when an item is accessed using the square bracket notation, e.g. arrayName[0]
. It is used to provide access to the items of an object.
Summary
There are many such special functions that can help developers easily customise and tweak functionality. Have a look at these functions and be amazed at the wonders it can do for you!