Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Base Overloading Methods in Python
Python provides special methods (also called magic methods or dunder methods) that you can override in your classes to customize their behavior. These methods allow your objects to work seamlessly with built-in functions and operators.
Common Base Overloading Methods
| Sr.No. | Method, Description & Sample Call |
|---|---|
| 1 |
__init__(self [,args...]) Constructor method called when creating an object Sample Call: obj = ClassName(args)
|
| 2 |
__del__(self) Destructor method called when object is garbage collected Sample Call: del obj
|
| 3 |
__repr__(self) Returns unambiguous string representation for developers Sample Call: repr(obj)
|
| 4 |
__str__(self) Returns human-readable string representation Sample Call: str(obj) or print(obj)
|
| 5 |
__len__(self) Returns length of object (replaces deprecated __cmp__) Sample Call: len(obj)
|
Example Implementation
Here's a practical example showing how to override these methods in a custom class ?
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"Student {name} created")
def __del__(self):
print(f"Student {self.name} deleted")
def __str__(self):
return f"Student: {self.name}, Age: {self.age}"
def __repr__(self):
return f"Student('{self.name}', {self.age})"
def __len__(self):
return len(self.name)
# Create and use the object
student = Student("Alice", 20)
print(str(student))
print(repr(student))
print(f"Name length: {len(student)}")
Student Alice created
Student: Alice, Age: 20
Student('Alice', 20)
Name length: 5
Student Alice deleted
Key Differences
| Method | Purpose | Target Audience |
|---|---|---|
__str__() |
Human-readable output | End users |
__repr__() |
Unambiguous representation | Developers |
__init__() |
Object initialization | Constructor |
Best Practices
When overriding these methods, follow these guidelines ?
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
# User-friendly format
return f"{self.title} ({self.pages} pages)"
def __repr__(self):
# Should be valid Python code if possible
return f"Book('{self.title}', {self.pages})"
def __len__(self):
return self.pages
book = Book("Python Guide", 300)
print(f"Book: {book}")
print(f"Representation: {repr(book)}")
print(f"Length: {len(book)} pages")
Book: Python Guide (300 pages)
Representation: Book('Python Guide', 300)
Length: 300 pages
Conclusion
Overriding special methods like __init__(), __str__(), and __repr__() makes your custom classes more intuitive and integrated with Python's built-in functions. Always implement __repr__() for debugging and __str__() for user-friendly output.
Advertisements
