0
0
Pythonprogramming~15 mins

Default values in constructors in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Default values in constructors
📖 Scenario: You are creating a simple program to manage information about books in a library. Each book has a title, an author, and a number of pages. Sometimes, the number of pages is not known when the book is added.
🎯 Goal: Build a Python class called Book that uses default values in its constructor to handle missing information. Then create a book object and display its details.
📋 What You'll Learn
Create a class named Book with a constructor that takes three parameters: title, author, and pages.
Set the default value of pages to 0 in the constructor.
Create an instance of Book named my_book with title 'Python Basics' and author 'John Doe', but do not provide the pages value.
Print the details of my_book in the format: Title: Python Basics, Author: John Doe, Pages: 0.
💡 Why This Matters
🌍 Real World
Default values in constructors help when some information is optional or unknown at first, like missing book pages in a library system.
💼 Career
Understanding default values in constructors is important for writing flexible and user-friendly classes in software development.
Progress0 / 4 steps
1
Create the Book class with a constructor
Create a class called Book with a constructor method __init__ that takes parameters title, author, and pages. Inside the constructor, assign these parameters to instance variables self.title, self.author, and self.pages.
Python
Need a hint?

Remember to use def __init__(self, ...) to create the constructor and assign parameters to self variables.

2
Add a default value for pages in the constructor
Modify the constructor of the Book class so that the parameter pages has a default value of 0. This means if no pages value is given when creating a book, it will automatically be set to zero.
Python
Need a hint?

Set the default value by writing pages=0 in the constructor parameters.

3
Create a Book object without pages value
Create an instance of the Book class named my_book with the title 'Python Basics' and author 'John Doe'. Do not provide the pages argument so it uses the default value.
Python
Need a hint?

Call Book with only two arguments: title and author.

4
Print the book details
Print the details of my_book in this exact format: Title: Python Basics, Author: John Doe, Pages: 0. Use an f-string to access my_book.title, my_book.author, and my_book.pages.
Python
Need a hint?

Use print(f"Title: {my_book.title}, Author: {my_book.author}, Pages: {my_book.pages}") to show the details.