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
Dunder or magic methods in python
Dunder methods (also called magic methods) are special methods in Python that allow us to define how objects behave with built-in operations. These methods are identified by double underscores (__) as prefix and suffix, like __init__ or __str__.
Basic Object Representation
Without defining custom string representation, Python objects display their memory location ?
class String:
# magic method to initiate object
def __init__(self, string):
self.string = string
# object creation
my_string = String('Python')
# print object location
print(my_string)
<__main__.String object at 0x000000BF0D411908>
Using __repr__ for String Representation
The __repr__ method defines the "official" string representation of an object ?
class String:
# magic method to initiate object
def __init__(self, string):
self.string = string
# print our string object
def __repr__(self):
return 'Object: {}'.format(self.string)
# object creation
my_string = String('Python')
# print object representation
print(my_string)
Object: Python
Adding Custom Operators with __add__
Without defining __add__, trying to use the + operator will raise an error ?
class String:
def __init__(self, string):
self.string = string
def __repr__(self):
return 'Object: {}'.format(self.string)
my_string = String('Python')
try:
print(my_string + ' Programming')
except TypeError as e:
print(f"TypeError: {e}")
TypeError: unsupported operand type(s) for +: 'String' and 'str'
Implementing __add__ Method
The __add__ method enables the + operator for our custom class ?
class String:
def __init__(self, string):
self.string = string
def __repr__(self):
return 'Object: {}'.format(self.string)
def __add__(self, other):
return self.string + other
# object creation
my_string = String('Hello')
# concatenate String object and a string
print(my_string + ' Python')
Hello Python
Common Dunder Methods
| Method | Purpose | Example Usage |
|---|---|---|
__init__ |
Object initialization | Constructor |
__repr__ |
Official string representation | repr(obj) |
__str__ |
Informal string representation | str(obj) |
__add__ |
Addition operator | obj1 + obj2 |
__len__ |
Length function | len(obj) |
Conclusion
Dunder methods provide a powerful way to customize object behavior in Python. They enable your custom classes to work seamlessly with built-in functions and operators, making your code more intuitive and Pythonic.
