0
0
Pythonprogramming~15 mins

Adding custom attributes in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Adding Custom Attributes to a Python Object
📖 Scenario: You are creating a simple program to store information about a book. You want to add extra details to the book object by adding custom attributes.
🎯 Goal: Build a Python program that creates a book object, adds a custom attribute to it, and then prints that attribute.
📋 What You'll Learn
Create a class called Book with a title attribute
Create an instance of Book called my_book with the title 'Python Basics'
Add a custom attribute called author to my_book with the value 'Alice'
Print the value of the author attribute from my_book
💡 Why This Matters
🌍 Real World
Adding custom attributes to objects is useful when you want to store extra information that was not planned when the class was first created.
💼 Career
Understanding how to add and use custom attributes helps in flexible software design and is common in many programming jobs involving object-oriented programming.
Progress0 / 4 steps
1
Create the Book class and an instance
Create a class called Book with an __init__ method that takes title as a parameter and sets it as an attribute. Then create an instance called my_book with the title 'Python Basics'.
Python
Need a hint?

Use class Book: to start the class. Inside, define def __init__(self, title): and set self.title = title. Then create my_book = Book('Python Basics').

2
Add a custom attribute to the book instance
Add a custom attribute called author to the my_book object and set its value to 'Alice'.
Python
Need a hint?

Use dot notation to add the attribute: my_book.author = 'Alice'.

3
Access the custom attribute
Write a line of code that accesses the author attribute from my_book and stores it in a variable called book_author.
Python
Need a hint?

Use book_author = my_book.author to get the author attribute.

4
Print the custom attribute
Print the value of the variable book_author.
Python
Need a hint?

Use print(book_author) to show the author.