Special Methods in Classes
In Python, Special Methods are predefined methods within a class that define the behavior of objects and assist in interaction with Python's built-in functions.
These methods are also known as Magic Methods, starting and ending with double underscores (__).
For example, you can represent an object as a string using (__str__) or compare two objects using (__eq__).
Examples of Using Special Methods
The code example below defines a Book class using the __str__ and __eq__ special methods.
The __str__ method is a special method that defines the string representation of an object, called when converting an object to a string using the print function or the str function.
Generally, the __str__ method is used to present the object's information in a human-readable format.
The __eq__ method is a special method that defines equality comparison between objects, executed when the == operator is used to compare two objects.
# Define class Book
class Book:
# Initialization method
def __init__(self, title, author):
self.title = title # Book title
self.author = author # Author name
# __str__ method: Converts the object into a human-readable string
def __str__(self):
return f"{self.title} by {self.author}" # Return with string formatting
# __eq__ method: Compares two objects based on title and author
def __eq__(self, other):
# Returns True if titles and authors are equal, otherwise False
return self.title == other.title and self.author == other.author
print(book1 == book3) # False
In this example, the __str__ method converts the object into a human-readable string, and the __eq__ method compares whether the title and author of two objects are the same.
Here is an example of how to create and use instances of the Book class:
# Create Book objects
book1 = Book("Harry Potter", "J.K. Rowling")
book2 = Book("Harry Potter", "J.K. Rowling")
book3 = Book("The Lord of the Rings", "J.R.R. Tolkien")
# __str__ method example: Outputs in a human-readable format when printing
print(book1)
# Outputs "Harry Potter by J.K. Rowling"
# __eq__ method example: Compare objects
print(book1 == book2)
# True, both objects have the same title and author
print(book1 == book3)
# False, different title and author
# Manage Book objects in a list
book_list = [book1, book2, book3]
# Output book information in the list (applies __str__ method to all objects)
for book in book_list:
print(book)
# Result:
# Harry Potter by J.K. Rowling
# Harry Potter by J.K. Rowling
# The Lord of the Rings by J.R.R. Tolkien
In the code above, book1, book2, and book3 are instances of the Book class.
The __str__ method allows objects to be displayed in a readable format when printed usingprint(book1).
The __eq__ method enables object comparison based on attributes, such as title and author, when using book1 == book2.
What are Some Special Methods?
-
__str__(self): Used to provide a string representation of an object. It's called by theprint()function or thestr()function. -
__eq__(self, other): Overrides the==operator to define equality comparison between objects. -
__ne__(self, other): Overrides the!=operator to compare differences between objects. -
__gt__(self, other): Overrides the>operator to define size comparison between objects. -
__ge__(self, other): Overrides the>=operator to define size comparison between objects. -
__lt__(self, other): Overrides the<operator to define size comparison between objects. -
__le__(self, other): Overrides the<=operator to define size comparison between objects.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.