Professional Documents
Culture Documents
Magic Method
Magic Method
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.
__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.
__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.
__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.
__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.
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}"
# Usage
book1 = Book("1984", "George Orwell")
book2 = Book("1984", "George Orwell")