You are on page 1of 2

In Python, special methods are a set of predefined methods you can use to enrich

your classes. They are also known as "magic methods" or "dunder" methods because
they start and end with double underscores (__). These methods allow us to emulate
the behavior of built-in types or to implement operator overloading.

The most commonly used special methods are:

__init__(self, [...]): The initializer for the class, called when an instance
(object) of the class is created. It's equivalent to a constructor in other OOP
languages.

__del__(self): Called when an instance is about to be destroyed. This is also known


as the destructor.

__repr__(self): Called by the repr() built-in function and by string conversions


(reverse quotes) to compute the "official" string representation of an object. This
is typically used for debugging and should ideally look like a valid Python
expression that could be used to recreate an object with the same value.

__str__(self): Called by the str() built-in function and by the print statement to
compute the "informal" or nicely printable string representation of an object.

__bytes__(self): Called by the bytes() to compute a byte-string representation of


an object.

__format__(self, format_spec): Called by the built-in format() function and the


str.format() method to produce a "formatted" string representation of an object.

__lt__(self, other), __le__(self, other), __eq__(self, other), __ne__(self, other),


__gt__(self, other), __ge__(self, other): These are comparison magic methods, used
to define the behavior of the comparison operators (<, <=, ==, !=, >, >=
respectively) for class instances.

__hash__(self): Called by the hash() built-in function to compute the hash value of
an object for operations on collections like set, frozenset, or dict.

__bool__(self): Called to implement truth value testing and the built-in operation
bool(); should return False or True.

__getattr__(self, name), __getattribute__(self, name), __setattr__(self, name,


value), and __delattr__(self, name): These are attribute access methods that Python
calls when an attribute is read, assigned, or deleted.

__getitem__(self, key), __setitem__(self, key, value), __delitem__(self, key):


Called to implement assignment, retrieval, and deletion of items using the square
brackets syntax for indexing (e.g., obj[key]).

__iter__(self), __next__(self): These methods are required for creating your own
iterator objects. They are used by the iter() and next() built-in functions.

Arithmetic operators like __add__(self, other), __sub__(self, other), __mul__(self,


other), etc., are called to implement arithmetic operators.

Here is an example of a class implementing some of these special methods:

python
Copy
class Book:
def __init__(self, title, author):
self.title = title
self.author = author

def __repr__(self):
return f"Book({self.title!r}, {self.author!r})"

def __str__(self):
return f"{self.title} by {self.author}"

def __eq__(self, other):


if isinstance(other, Book):
return (self.title == other.title) and (self.author == other.author)
return NotImplemented

# Usage
book1 = Book("1984", "George Orwell")
book2 = Book("1984", "George Orwell")

print(book1) # Calls __str__: 1984 by George Orwell


print(repr(book1)) # Calls __repr__: Book('1984', 'George Orwell')
print(book1 == book2) # Calls __eq__: True
In practice, you should implement __repr__ in a way that the output, when passed to
eval(), should (ideally) create an object with the same properties. This is not
always feasible, but it's a good guideline. The __str__ method, on the other hand,
should return a string that is readable and concise, intended for end-users.

You might also like