Introduction:
Classes in Python are fundamental to object-oriented programming. This example demonstrates class creation and object-oriented programming concepts by defining a simple car class.
Code:
pythonCopy codeclass Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
self.mileage = 0
def show_info(self):
print(f"Car: {self.brand} {self.model} ({self.year})")
print(f"Mileage: {self.mileage} km")
def add_mileage(self, km):
if km >= 0:
self.mileage += km
print(f"Mileage increased by {km} km.")
else:
print("You entered a negative value. Mileage increase failed.")
# Sample usage
car1 = Car("Toyota", "Corolla", 2020)
car1.show_info()
car1.add_mileage(100)
car1.show_info()
car1.add_mileage(-20) # Negative mileage increase
car1.show_info()
Explanation:
In the provided code, a class named "Car" is defined. It specifies properties such as brand, model, year, and mileage for each car. The init
method is the constructor of the class, called when a Car object is instantiated. The show_info
method displays the car's details, while the add_mileage
method updates the car's mileage.
Result:
This example illustrates how to create a simple car class and how to utilize it. Classes and object-oriented programming enable us to manage complex systems in a more modular and organized manner.