In Python, special functions are functions with double underscores on both sides of the function name. They are also known as “magic methods” or “dunder methods” (short for “double underscore” methods). These functions provide a way to customize the behavior of Python classes, enabling them to mimic built-in types or interact with specific language features. Some common special functions include __init__
, __str__
, __repr__
, __len__
, etc.
The syntax for defining special functions is as follows:
def __special_function__(self, ...):
# Code for the special function
# You can access and manipulate the object's attributes here
Here’s a breakdown of the syntax:
- The special function starts with
__
(double underscores) on both sides of the function name. - The function name itself follows the Python identifier naming conventions, with any additional information you may choose to include.
- The first parameter of a special function is typically
self
, which refers to the instance of the class. It is automatically passed when the special function is called. - Additional parameters can be included in the special function as needed, based on the specific functionality you want to achieve.
- Inside the special function, you can access and manipulate the object’s attributes using the
self
keyword, just like in regular methods.
Here are some commonly used special functions in Python:
Special Function | Description |
---|---|
__init__(self, ...) | Constructor method. Initializes object attributes. |
__str__(self) | Returns a string representation of the object. |
__repr__(self) | Returns a developer-friendly string representation. |
__len__(self) | Returns the length of the object (used with containers). |
__getitem__(self, key) | Gets an item using square bracket notation. |
__setitem__(self, key, value) | Sets an item using square bracket notation. |
__delitem__(self, key) | Deletes an item using the del statement. |
__contains__(self, item) | Implements the in operator. |
__call__(self, ...) | Enables the object to be called as a function. |
__eq__(self, other) | Implements equality using the == operator. |
__ne__(self, other) | Implements inequality using the != operator. |
__lt__(self, other) | Implements less-than using the < operator. |
__le__(self, other) | Implements less-than or equal using the <= operator. |
__gt__(self, other) | Implements greater-than using the > operator. |
__ge__(self, other) | Implements greater-than or equal using the >= operator. |
__add__(self, other) | Implements addition using the + operator. |
__sub__(self, other) | Implements subtraction using the - operator. |
__mul__(self, other) | Implements multiplication using the * operator. |
__div__(self, other) | Implements division using the / operator (deprecated in Python 3). |
__truediv__(self, other) | Implements true division using the / operator. |
__mod__(self, other) | Implements modulo using the % operator. |
__pow__(self, other) | Implements exponentiation using the ** operator. |
Note: this table is not exhaustive, and there are more special functions that you can use in Python classes depending on your specific requirements.
Python Special Functions
Let’s explore some more examples of Python’s special functions:
Example 1: __len__
(Getting the Length of an Object)
class MyList:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
my_list = MyList([1, 2, 3, 4, 5])
print(len(my_list)) # Output: 5
In this example, we defined a custom class MyList
with a special function __len__
. When we use the len()
function on an instance of MyList
, it calls the __len__
special function to get the length of the data
attribute.
Example 2: __getitem__
(Getting Items from an Object)
class MyDictionary:
def __init__(self):
self.data = {}
def __setitem__(self, key, value):
self.data[key] = value
def __getitem__(self, key):
return self.data.get(key)
my_dict = MyDictionary()
my_dict['name'] = 'John'
my_dict['age'] = 30
print(my_dict['name']) # Output: John
print(my_dict['age']) # Output: 30
print(my_dict['city']) # Output: None (key not present in the dictionary)
In this example, we defined a custom class MyDictionary
with __setitem__
and __getitem__
special functions. When we use square brackets to set or get an item on an instance of MyDictionary
, it calls these special functions to handle the operation.
Example 3: __str__
and __repr__
(String Representations)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
point = Point(3, 5)
print(str(point))
print(repr(point))
Output:
In this example, we defined a custom class Point
with __str__
and __repr__
special functions. The __str__
function provides a human-readable string representation of the object, while __repr__
provides a developer-friendly representation that can be used to recreate the object.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.