0
0
Pythonprogramming~15 mins

Constructor parameters in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Constructor parameters
📖 Scenario: You are creating a simple program to manage information about books in a library. Each book has a title and an author.
🎯 Goal: You will build a Python class called Book that uses constructor parameters to set the title and author when creating a new book object.
📋 What You'll Learn
Create a class named Book
Add a constructor method __init__ with parameters title and author
Store the title and author as instance variables
Create an instance of Book with title '1984' and author 'George Orwell'
Print the book's title and author
💡 Why This Matters
🌍 Real World
Classes with constructors are used to create objects that represent real things, like books, users, or products, with their own data.
💼 Career
Understanding constructors is essential for software development jobs where object-oriented programming is used to organize code and data.
Progress0 / 4 steps
1
Create the Book class with an empty constructor
Create a class called Book with a constructor method __init__ that takes self as the only parameter. Inside the constructor, write pass to keep it empty for now.
Python
Need a hint?

Remember, a constructor method in Python is named __init__ and always has self as the first parameter.

2
Add title and author parameters to the constructor
Modify the __init__ method to accept two parameters: title and author, in addition to self. Inside the constructor, assign these parameters to instance variables self.title and self.author.
Python
Need a hint?

Use self.title = title and self.author = author inside the constructor to save the values.

3
Create a Book object with title and author
Create a variable called my_book and assign it a new Book object with the title '1984' and author 'George Orwell'.
Python
Need a hint?

Use my_book = Book('1984', 'George Orwell') to create the object.

4
Print the book's title and author
Write a print statement that outputs the book's title and author in the format: Title: 1984, Author: George Orwell using the my_book object.
Python
Need a hint?

Use an f-string like print(f"Title: {my_book.title}, Author: {my_book.author}") to show the values.