Python Data Science Jobs & Interviews
20.4K subscribers
188 photos
4 videos
25 files
326 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
How can you design a Python class to represent a geometric shape (e.g., Circle, Rectangle) with inheritance and method overriding, ensuring each shape calculates its area and perimeter correctly? Implement a base class Shape with abstract methods for area and perimeter, then create derived classes for Circle and Rectangle. Include validation for input parameters and demonstrate polymorphism by storing multiple shapes in a list and iterating through them to calculate total area and perimeter.

from abc import ABC, abstractmethod
import math

class Shape(ABC):
"""Abstract base class for geometric shapes."""

@abstractmethod
def area(self) -> float:
"""Calculate the area of the shape."""
pass

@abstractmethod
def perimeter(self) -> float:
"""Calculate the perimeter of the shape."""
pass

class Circle(Shape):
"""Represents a circle with a given radius."""

def __init__(self, radius: float):
if radius <= 0:
raise ValueError("Radius must be positive.")
self.radius = radius

def area(self) -> float:
return math.pi * self.radius ** 2

def perimeter(self) -> float:
return 2 * math.pi * self.radius

class Rectangle(Shape):
"""Represents a rectangle with width and height."""

def __init__(self, width: float, height: float):
if width <= 0 or height <= 0:
raise ValueError("Width and height must be positive.")
self.width = width
self.height = height

def area(self) -> float:
return self.width * self.height

def perimeter(self) -> float:
return 2 * (self.width + self.height)

# Example usage
shapes = [
Circle(5),
Rectangle(4, 6),
Circle(3),
Rectangle(7, 2)
]

total_area = 0
total_perimeter = 0

for shape in shapes:
total_area += shape.area()
total_perimeter += shape.perimeter()

print(f"Total Area: {total_area:.2f}")
print(f"Total Perimeter: {total_perimeter:.2f}")

# Demonstrate polymorphism
for shape in shapes:
print(f"{shape.__class__.__name__}: Area = {shape.area():.2f}, Perimeter = {shape.perimeter():.2f}")

Answer: The question explores object-oriented programming concepts in Python using inheritance and abstraction. The solution defines an abstract base class Shape with two abstract methods (area and perimeter) that must be implemented by all derived classes. Two concrete classes, Circle and Rectangle, inherit from Shape and provide their own implementations of the required methods. Input validation is enforced through error checking in the constructors. The example demonstrates polymorphism by storing different shape types in a single list and processing them uniformly. This approach promotes code reusability, maintainability, and extensibility, making it ideal for academic and real-world applications involving geometric calculations.

#Python #OOP #Inheritance #Polymorphism #Abstraction #GeometricShapes #Programming #Academic #IntermediateLevel #ObjectOriented

By: @DataScienceQ 🚀
2