0
0
Pythonprogramming~30 mins

Class methods and cls usage in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Class methods and cls usage
📖 Scenario: Imagine you are creating a simple system to track how many books have been added to a library. Each book has a title and an author. You want to keep count of all books created using a class method.
🎯 Goal: You will build a Book class that keeps track of the total number of books created using a class method and the cls keyword.
📋 What You'll Learn
Create a class called Book with attributes title and author
Add a class variable count to track the number of books
Create a class method called increment_count that increases count by 1 using cls
Use the class method inside the constructor to update the count each time a new book is created
Print the total number of books using the class variable
💡 Why This Matters
🌍 Real World
Tracking counts of objects like books, users, or orders is common in software. Class methods help manage data shared across all objects.
💼 Career
Understanding class methods and class variables is important for writing clean, organized code in many programming jobs, especially in object-oriented programming.
Progress0 / 4 steps
1
Create the Book class with attributes
Create a class called Book with an __init__ method that takes self, title, and author as parameters. Inside __init__, set self.title to title and self.author to author.
Python
Need a hint?

Remember to use self to set instance variables inside __init__.

2
Add a class variable and class method
Add a class variable called count to Book and set it to 0. Then create a class method called increment_count using the @classmethod decorator. It should take cls as a parameter and increase cls.count by 1.
Python
Need a hint?

Use @classmethod above the method and cls.count += 1 inside it.

3
Call the class method inside the constructor
Inside the __init__ method, call the class method increment_count using Book.increment_count() to update the book count whenever a new book is created.
Python
Need a hint?

Call the class method inside __init__ using the class name Book.increment_count().

4
Create books and print total count
Create three Book objects with any titles and authors you like. Then print the total number of books by printing Book.count.
Python
Need a hint?

Create three books and print Book.count to see the total.