macro shot photography of water drops

Python Classes: Creating Cars with Unique Colors and Default Mileage

Introduction

When designing classes in object-oriented programming, it’s essential to clearly distinguish between what should be shared among all instances and what should be unique to each instance. Let’s take a common real-world example — creating a Car class. Each car can be of a different color, but all cars should start with zero mileage. The way we structure this class determines its scalability, maintainability, and clarity. Let’s explore how to do this right in Python.

Master Python: 600+ Real Coding Interview Questions
Master Python: 600+ Real Coding Interview Questions

Write Mid-Section here

The Scenario Explained

Imagine a car manufacturing system where:

  • Each car has its own color (like red, blue, or black).
  • All cars, when newly created, should begin with a mileage of zero.

This leads to a simple class design challenge:
How do we assign color uniquely per car while making mileage start at zero for every car?


The Best Way to Handle Initialization

In Python, instance variables are best used when we want each object to have its own values. Here’s how we can implement this:

class Car:
def __init__(self, color):
self.color = color # unique per car
self.mileage = 0 # shared default, but still per instance

Why this works well:

  • self.color takes a unique input during object creation.
  • self.mileage is initialized to 0 for every car, ensuring consistency, but it’s not shared — it’s an instance variable, not a class variable.

Creating Cars with Unique Colors and Default Mileage

car1 = Car("Red")
car2 = Car("Blue")

print(car1.color, car1.mileage) # Red 0
print(car2.color, car2.mileage) # Blue 0

Each car gets its own color and starts with 0 mileage — exactly what we want.

Machine Learning & Data Science 600+ Real Interview Questions
Machine Learning & Data Science 600 Real Interview Questions

Write text here

What to Avoid

A common mistake is using a class variable for mileage like this:

class Car:
mileage = 0 # class variable (shared across all instances)
def __init__(self, color):
self.color = color

This would cause problems if you try to increment mileage later, as all cars will share the same mileage, which is not the behavior we want.

Master LLM and Gen AI: 600+ Real Interview Questions
Master LLM and Gen AI: 600+ Real Interview Questions

Conclusion

In object-oriented design, understanding the difference between instance and class variables is key. For our Car class:

  • Color varies per car — so it’s set via the constructor.
  • Mileage starts at the same value (zero), but it should still be an instance variable so each car tracks its own usage.

By using __init__ correctly, we ensure our code is flexible, correct, and future-proof.

Leave a Reply