Welcome to another exciting lesson on CodeYourCraft! Today, we're diving deep into the concept of Abstraction in Python. Let's get started! 🚀
Abstraction is a process of hiding the complexities and showing only the essential features of an object or a system. In Python, we achieve abstraction using classes and objects.
Why is abstraction important? It makes our code easier to understand, maintain, and reuse. By abstracting complexities, we can focus on the problem at hand instead of getting lost in details. 💡
In Python, classes are used to create objects that represent real-world or abstract concepts. Here's a simple example of a class:
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = yearIn this example, we created a class named Car with three attributes (brand, model, year). The __init__ method is a special method that Python calls when an object is created from a class.
Now that we have a Car class, we can create objects (cars) from it:
my_car = Car("Toyota", "Camry", 2020)
print(my_car.brand) # Output: ToyotaWe can also define methods in a class that perform specific tasks related to the object. Here's an example of a method that prints car details:
class Car:
# ... (previous code)
def print_details(self):
print(f"Brand: {self.brand}")
print(f"Model: {self.model}")
print(f"Year: {self.year}")
my_car.print_details()Output:
Brand: Toyota
Model: Camry
Year: 2020
Now let's see how abstraction comes into play. Imagine we want to add a new feature to our Car class: a method that calculates the car's depreciation each year.
Instead of hardcoding the depreciation formula directly into the Car class, we can create an abstract method (a method without implementation) and let the user of the class provide the specific depreciation formula.
class Car:
# ... (previous code)
def depreciate(self, depreciation_rate):
# This is an abstract method, the user will provide its implementation
pass
def print_depreciation(self):
self.depreciate(0.2) # Here we're assuming a depreciation rate of 20%
print(f"Depreciation: {self.year * 0.2}")Now, when a user wants to create a car and calculate its depreciation, they need to provide the implementation of the depreciate method:
class ToyotaCar(Car):
def depreciate(self, depreciation_rate):
super().depreciate(depreciation_rate) # Call the parent class's depreciate method
if self.year < 5:
self.year -= depreciation_rate * self.year # Custom depreciation rule for Toyota cars
my_toyota_car = ToyotaCar("Toyota", "Camry", 2020)
my_toyota_car.print_depreciation() # Output: Depreciation: 4.0By using abstraction, we've made our code more flexible and adaptable to specific use cases. ✅
What is Abstraction in Python?
What does the `__init__` method do in Python classes?