Everything in Python is an object and we define objects through classes. When we define an object, we actually create an instance of a class. Thus, class is the most fundamental piece in Python.
Classes have:
- Data attributes: Define what is needed to create an instance of a class
- Methods (i.e. procedural attributes): Define how to interact with the instances of a class
We can create our own classes using data and procedural attributes. It is our playground so we can implement various functions to customize a class.
In addition to the user-defined functions, it is possible to use built-in Python function within user-defined classes. This is what special (or magic) methods are for.
Special methods allow for using the built-in Python functions to enrich user-defined classes. Consider the print function which is one of the most commonly used Python function. If you use it to print an instance of your class, it will print out something like the following:
<__main__.Book object at 0x7f9ed5b1d590>
It displays the name of the class (Book) and the memory location of the object which is not a proper use of the print function. We can customize its behavior by implementing the str special method in our class.
In this article, we will go over 4 special methods that you will be likely to use in your classes.
1. init
The init special method is automatically executed when an instance of class is created. It is also called class constructor. The parameters of the init represent the data attributes of a class.
Let’s create a class called Book.
class Book():
def __init__(self, name, writer, pages):
self.name = name
self.writer = writer
self.pages = pages
The self refers to the instance itself. The Book class has 3 data attributes that need to be specified when creating a Book instance.
b = Book("Moby Dick", "Herman Melville", "378")
type(b)
__main__.Book
The variable b is an instance of the Book class.
2. str
We use the str special method to implement the built-in print function within our class. Without the str, here is what print function does.
print(b)
<__main__.Book object at 0x7f9ed5b1d590>
Let’s define the str method in our class definition.
def __str__(self):
return f"The title of the book is {self.name}"
Now the print function will return the title of the name. It accesses the name of the book through the name attribute. You can customize it in any way you’d like.
print(b)
The title of the book is Moby Dick
3. len
The len function returns the length of an object. For strings, it returns the number of characters. For a Pandas data frame, it returns the number of row.
We can customize its behavior by implementing the len special method in our class definition. Let’s make it to return the number of pages of a book object.
If the len is not implemented in the class definition, you will get an error if you try to use it on an object of your class. It does not have a default behavior like the print function.
def __len__(self):
return int(self.pages)
len(b)
378
Please note that each time you add a new function to your class, you need to recreate the object to be able to use the new functions.
4. eq
The eq special method allows for comparing two instances of a class. If it is defined in our class, we can check if an instance is equal to another instance. The equality condition is specified using the eq method.
In our case, we can declare two books being equal if the names and writers of the book are the same. They might have different number of pages.
def __eq__(self, other):
return (self.name == other.name) & (self.writer == other.writer)
The "==" operator will return True if both names and writes are the same for two instances. Let’s create two books and check if they are equal.
b = Book("Moby Dick", "Herman Melville", "378")
a = Book("Moby Dick", "Herman Melville", "410")
b == a
True
If either names or writes is different, the equality operator returns False.
b = Book("Moby Dick", "Herman Melville", "378")
a = Book("Moby Dick", "Melville", "410")
b == a
False
Conclusion
Objects are at the core of Python so creating robust, function, and well-designed classes are of crucial importance. We have covered 4 special methods that you will need to implement in your own classes.
Thank you for reading. Please let me know if you have any feedback.