Abstraction in object-oriented programming is a technique to hide complex implementation details and show only essential information to the user. It provides a simplified view of an object.
class Shape:
def __init__(self, name):
self.name = name
def area(self):
raise NotImplementedError("Subclasses must implement this method")
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
def area(self):
return 3.14159 * self.radius * self.radius
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__("Rectangle")
self.width = width
self.height = height
def area(self):
return self.width * self.height
circle = Circle(5)
rectangle = Rectangle(4, 6)
print(circle.area()) # Output: Area of circle
print(rectangle.area()) # Output: Area of rectangle
The `Shape` class defines a common interface (`area()`). The derived classes (e.g., `Circle`) provide the specific implementation details for calculating the area.
class MyClass:
def __init__(self):
self._internal_data = 10 # Protected attribute
def get_data(self):
return self._internal_data
def set_data(self, value):
self._internal_data = value
obj = MyClass()
print(obj.get_data()) #Output: 10
obj.set_data(20) #Modify the internal value.
print(obj.get_data()) #Output: 20
#print(obj._internal_data) # Accessing the protected attribute directly is discouraged.
Internal data (_internal_data
) is protected through the getter (`get_data()`) and setter (`set_data()`) methods. This controls how the data is accessed and modified.
from abc import ABC, abstractmethod
#Import abstract base class from module
class Vehicle(ABC): #Abstract base class
@abstractmethod #Forces derived classes to implement method
def start(self):
pass
class Car(Vehicle):
def start(self):
print("Car engine started")
car = Car()
car.start() #Output: Car engine started