Special Methods — Python Like You Mean It
Python Built-In Methods: Comprehensive List
Python Built-In Methods Examples
Python's object-oriented programming (OOP) paradigm provides ways to define methods that allow for more intuitive and flexible interactions between different objects. These methods are called "special methods" or "magic methods". They are special because they have double underscores before and after their names.
In Python, special methods (also known as magic methods or dunder methods) are identified by double underscores (e.g., __init__
, __str__
, __add__
). These methods allow you to define specific behaviors for your objects. Here's a list of some commonly used special methods:
__repr__(self)
: Developer-friendly representation of an object when using repr(obj)
.
The __repr__()
method is called when an object is printed using the built-in repr()
function. It should return a string representation of the object that can be used to recreate the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person('{self.name}', {self.age})"
person = Person("Alice", 30)
print(repr(person)) # Output: Person('Alice', 30)
__len__(self)
: Defines the behavior when calling len(obj)
.
The __len__()
method is used to return the length of the object. It is called when the built-in len()
function is used on the object.
class CustomList:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
custom_list = CustomList([1, 2, 3, 4, 5])
print(len(custom_list)) # Output: 5
__getitem__(self, key)
: Used to get an item using square brackets, e.g., obj[key]
.
The __getitem__()
method is used to define the behavior when an item is accessed using square brackets, e.g., obj[key]
.
class MyList:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
my_list = MyList([1, 2, 3, 4, 5])
print(my_list[2]) # Output: 3
__setitem__(self, key, value)
: Used to set an item using square brackets, e.g., obj[key] = value
.
The __setitem__()
method is used to define the behavior when an item is set using square brackets, e.g., obj[key] = value
.
class MyList:
def __init__(self, data):
self.data = data
def __setitem__(self, index, value):
self.data[index] = value
def __str__(self):
return str(self.data)
my_list = MyList([1, 2, 3])
my_list[1] = 5
print(my_list) # Output: [1, 5, 3]
__delitem__(self, key)
: Used