Python Tutorial: Special Methods in Classes π§βπ»
Table of Contents π
- Introduction to Special Methods
- The
__init__
Method π οΈ - Example: Initializing Objects
- The
__str__
and__repr__
Methods π - Example: String Representation of Objects
- The
__len__
Method π - Example: Custom Length Calculation
- The
__getitem__
and__setitem__
Methods π― - Example: Indexing and Assignment
- The
__eq__
,__lt__
, and Other Comparison Methods βοΈ - Example: Custom Comparison
- The
__call__
Method βοΈ - Example: Making Instances Callable
- The
__del__
Method ποΈ - Example: Cleanup Actions
- Summary π
1. Introduction to Special Methods
Special methods in Python, also known as "dunder" methods (short for double underscores), allow you to define the behavior of your class objects in various situations. These methods start and end with double underscores (e.g., __str__
, __init__
). By implementing these methods, you can control how your objects are represented, compared, indexed, and more.
2. The __init__
Method π οΈ
The __init__
method is the constructor in Python. It is called when an instance of the class is created, allowing you to initialize the object's attributes.
Example: Initializing Objects
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
my_dog = Dog("Buddy", 5)
print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 5
3. The __str__
and __repr__
Methods π
__str__
: Defines the human-readable string representation of an object. Used byprint()
andstr()
.__repr__
: Defines the official string representation of an object. Used byrepr()
and often in interactive shells.
Example: String Representation of Objects
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old."
def __repr__(self):
return f"Dog('{self.name}', {self.age})"
my_dog = Dog("Buddy", 5)
print(my_dog) # Output: Buddy is 5 years old.
print(repr(my_dog)) # Output: Dog('Buddy', 5)
4. The __len__
Method π
The __len__
method allows you to define a custom way to calculate the length of an object, which can be used by the len()
function.
Example: Custom Length Calculation
class PackOfDogs:
def __init__(self, *dogs):
self.dogs = dogs
def __len__(self):
return len(self.dogs)
pack = PackOfDogs("Buddy", "Max", "Bella")
print(len(pack)) # Output: 3
5. The __getitem__
and __setitem__
Methods π―
__getitem__
: Allows your objects to be indexed like lists or dictionaries.__setitem__
: Allows you to set values for specific indices.
Example: Indexing and Assignment
class PackOfDogs:
def __init__(self, *dogs):
self.dogs = list(dogs)
def __getitem__(self, index):
return self.dogs[index]
def __setitem__(self, index, value):
self.dogs[index] = value
pack = PackOfDogs("Buddy", "Max", "Bella")
print(pack[0]) # Output: Buddy
pack[1] = "Rocky"
print(pack[1]) # Output: Rocky
6. The __eq__
, __lt__
, and Other Comparison Methods βοΈ
Python allows you to define custom comparison logic by implementing the following methods:
__eq__(self, other)
: Equal to (==
)__lt__(self, other)
: Less than (<
)__le__(self, other)
: Less than or equal to (<=
)__gt__(self, other)
: Greater than (>
)__ge__(self, other)
: Greater than or equal to (>=
)__ne__(self, other)
: Not equal to (!=
)
Example: Custom Comparison
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age
def __lt__(self, other):
return self.age < other.age
dog1 = Dog("Buddy", 5)
dog2 = Dog("Max", 7)
print(dog1 == dog2) # Output: False
print(dog1 < dog2) # Output: True
7. The __call__
Method βοΈ
The __call__
method allows an instance of a class to be called as a function.
Example: Making Instances Callable
class Dog:
def __init__(self, name):
self.name = name
def __call__(self, sound):
return f"{self.name} says {sound}"
my_dog = Dog("Buddy")
print(my_dog("Woof")) # Output: Buddy says Woof
8. The __del__
Method ποΈ
The __del__
method is called when an object is about to be destroyed. Itβs the destructor method in Python, and can be used to clean up resources like closing files or network connections.
Example: Cleanup Actions
class Dog:
def __init__(self, name):
self.name = name
print(f"{self.name} has been created.")
def __del__(self):
print(f"{self.name} has been destroyed.")
my_dog = Dog("Buddy")
del my_dog # Output: Buddy has been destroyed.
9. Summary π
Special methods, or dunder methods, are a powerful feature in Python that allows you to define the behavior of your objects in various situations. From initialization (__init__
) to string representation (__str__
and __repr__
), indexing (__getitem__
), comparison (__eq__
, __lt__
), and even callable instances (__call__
), these methods give you control over how your objects behave and interact in different contexts.