0
0
Pythonprogramming~15 mins

Class attributes in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Class Attributes in Python
📖 Scenario: Imagine you are creating a simple program to keep track of cars in a parking lot. Each car has its own color and model, but all cars share the same parking lot name.
🎯 Goal: You will create a class called Car with a class attribute for the parking lot name. Then, you will create individual cars with their own colors and models, and finally print the parking lot name.
📋 What You'll Learn
Create a class called Car
Add a class attribute called parking_lot with the value 'Central Parking'
Create two instances of Car with different color and model attributes
Print the class attribute parking_lot from one of the instances
💡 Why This Matters
🌍 Real World
Class attributes are useful when you want to store information that is the same for all objects of a class, like a company name or a shared setting.
💼 Career
Understanding class attributes is important for writing clean and efficient object-oriented code, which is common in software development jobs.
Progress0 / 4 steps
1
Create the Car class with no attributes
Write a class called Car with no attributes or methods yet.
Python
Need a hint?

Use the class keyword followed by the class name Car and a colon.

2
Add a class attribute parking_lot
Inside the Car class, add a class attribute called parking_lot and set it to the string 'Central Parking'.
Python
Need a hint?

Class attributes are defined directly inside the class, but outside any methods.

3
Create two Car instances with color and model
Create two variables called car1 and car2 that are instances of the Car class. Then add instance attributes color and model to each car with these exact values:
car1.color = 'red', car1.model = 'sedan', car2.color = 'blue', car2.model = 'suv'.
Python
Need a hint?

Create instances by calling the class name with parentheses, then add attributes using dot notation.

4
Print the class attribute parking_lot from car1
Write a print statement to display the value of the class attribute parking_lot using the instance car1.
Python
Need a hint?

Use print(car1.parking_lot) to access the class attribute from the instance.