0
0
Pythonprogramming~15 mins

Instance attributes in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Instance Attributes
📖 Scenario: You are creating a simple program to store information about books in a library. Each book has a title and an author.
🎯 Goal: Build a Python class called Book that uses instance attributes to store the title and author of each book. Then create one book object and print its details.
📋 What You'll Learn
Create a class named Book
Add an __init__ method with parameters self, title, and author
Inside __init__, set instance attributes self.title and self.author
Create an instance of Book named my_book with title '1984' and author 'George Orwell'
Print the title and author of my_book in the format: Title: 1984, Author: George Orwell
💡 Why This Matters
🌍 Real World
Storing information about objects like books, users, or products is common in software. Instance attributes let each object keep its own data.
💼 Career
Understanding instance attributes is essential for working with classes and objects in Python, a key skill for many programming jobs.
Progress0 / 4 steps
1
Create the Book class with an __init__ method
Create a class called Book with an __init__ method that takes self, title, and author as parameters. Inside __init__, set the instance attributes self.title and self.author to the values of title and author respectively.
Python
Need a hint?

Remember, self refers to the current object. Use it to store the title and author as instance attributes.

2
Create an instance of Book
Create an instance of the Book class named my_book with the title '1984' and author 'George Orwell'.
Python
Need a hint?

Use the class name Book followed by parentheses with the title and author as arguments.

3
Access instance attributes
Use my_book.title and my_book.author to access the title and author of the book.
Python
Need a hint?

Use dot notation to get the values stored in the instance attributes.

4
Print the book details
Print the title and author of my_book in the format: Title: 1984, Author: George Orwell using an f-string.
Python
Need a hint?

Use print(f"Title: {title}, Author: {author}") to display the book details.