Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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
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
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
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
Hint
Use print(f"Title: {my_book.title}, Author: {my_book.author}, Pages: {my_book.pages}") to show the details.
Practice
(1/5)
1. What is the main purpose of using default values in a Python class constructor (__init__ method)?
easy
A. To prevent the class from being instantiated
B. To make the constructor run faster
C. To allow creating objects without providing all arguments
D. To force the user to always provide all arguments
Solution
Step 1: Understand default values in constructors
Default values let you set a value for a parameter if no argument is given when creating an object.
Step 2: Identify the effect on object creation
This means you can create an object without giving all arguments, and the defaults fill in the missing ones.
Final Answer:
To allow creating objects without providing all arguments -> Option C
Quick Check:
Default values = optional arguments [OK]
Hint: Defaults let you skip arguments when creating objects [OK]
Common Mistakes:
Thinking defaults speed up the constructor
Believing defaults prevent object creation
Assuming defaults force all arguments
2. Which of the following is the correct way to set a default value for the parameter age in a Python class constructor?
easy
A. def __init__(self, age:30):
B. def __init__(self, age): age=30
C. def __init__(self, age): age == 30
D. def __init__(self, age=30):
Solution
Step 1: Recall Python syntax for default parameters
Default values are set by assigning a value in the parameter list, like age=30.
Step 2: Check each option
def __init__(self, age=30): uses correct syntax. def __init__(self, age): age=30 tries to assign inside the method header, which is invalid. def __init__(self, age): age == 30 uses comparison operator instead of assignment. def __init__(self, age:30): uses incorrect type hint syntax.
Final Answer:
def __init__(self, age=30): -> Option D
Quick Check:
Default parameter = param=value [OK]
Hint: Default values go in the parameter list with = [OK]
Common Mistakes:
Assigning default inside the method body
Using == instead of = for defaults
Confusing type hints with default values
3. What will be the output of this code?
class Person:
def __init__(self, name, age=25):
self.name = name
self.age = age
p = Person('Alice')
print(p.name, p.age)
medium
A. Alice 25
B. Alice None
C. Alice 0
D. Error: missing argument for age
Solution
Step 1: Analyze the constructor parameters
The constructor has age=25 as a default, so if age is not given, it uses 25.
Step 2: Check object creation and print
We create p = Person('Alice') without age, so age is 25. Printing p.name and p.age shows 'Alice 25'.
Final Answer:
Alice 25 -> Option A
Quick Check:
Missing argument uses default [OK]
Hint: Missing argument uses default value [OK]
Common Mistakes:
Expecting error when argument is missing
Assuming default is None if not given
Confusing default with zero or empty string
4. Find the error in this class constructor:
class Car:
def __init__(self, model='Sedan', year):
self.model = model
self.year = year
medium
A. Missing return statement in __init__
B. Default parameter must come after non-default parameters
C. self is missing in parameters
D. Cannot assign to self attributes in constructor
Solution
Step 1: Check parameter order in constructor
In Python, parameters with default values must come after parameters without defaults.
Step 2: Identify the error in parameter order
Here, model='Sedan' is a default parameter before year which has no default. This causes a syntax error.
Final Answer:
Default parameter must come after non-default parameters -> Option B
Quick Check:
Default params last in list [OK]
Hint: Put all default parameters after non-default ones [OK]
Common Mistakes:
Placing default parameters before required ones
Thinking __init__ needs return
Forgetting self parameter
5. You want to create a class Book where the author defaults to 'Unknown' and pages defaults to 100 if not provided. Which constructor is correct?