Let's talk in more details about methods, which were briefly mentioned earlier. In addition to the __init__ method we talked about before, we can also include any other methods we want for our classes. Methods are just another type of attribute, and you can think of them as functions that only objects of the same class can use. Let's look at an example with our book class (remember you still have to fill some of this out yourself in the file you downloaded):
class Book:
def __init__(self, genre, title, author, publication_year):
self.genre = genre
self.title = title
self.author = author
self.publication_year = publication_year
def calculate_age(self):
return 2022 - self.publication_year
For our class, we have added a new method, called calculate_age. It returns the age of our book based on the current year (2022) and its year of publication.
To invoke our method, the most obvious way is as follows:
ranger_games = Book('Crime Nonfiction', 'Ranger Games', 'Ben Blum', 2017)
print(Book.calculate_age(ranger_games))
This code tells the Book class to run the calculate_age method on the instance of the Book class called ranger_games.
Try running the code on PythonTutor at this link.
Another way to do the exact same thing is to tell the instance itself to do the age calculation:
ranger_games = Book('Crime Nonfiction', 'Ranger Games', 'Ben Blum', 2017)
ranger_games.calculate_age()
This alternate syntax is EXACTLY identical in behavior.
Try running this alternate version of the code in Python Tutor at this link.
There are a few important things worth noting: