0% found this document useful (0 votes)
11 views2 pages

Abstract Classes

ABSTRACT CLASSES

Uploaded by

nagaraju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Abstract Classes

ABSTRACT CLASSES

Uploaded by

nagaraju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Abstract Classes:

 An abstract class is a blueprint for other classes, defining a common interface and potentially
some shared implementation.
 It cannot be instantiated directly; its purpose is to be inherited by other "concrete" classes.
 In Python, abstract classes are created by inheriting from ABC (Abstract Base Class) from the
abc module.
 Abstract classes can contain both abstract methods (without implementation) and concrete
methods (with implementation).

Abstract Methods:

 An abstract method is a method declared within an abstract class but without any implementation
body.
 It serves as a contract, requiring any concrete subclass to provide its own implementation for that
method.
 In Python, abstract methods are marked with the @abstractmethod decorator from the abc
module. [1]

Purpose and Benefits:

 Enforce Structure: Abstract classes and methods ensure that subclasses adhere to a predefined
interface, promoting consistency and maintainability in object-oriented design.
 Define Common Behavior: Abstract classes can provide common methods and attributes, while
abstract methods force subclasses to implement specific functionalities relevant to their unique
nature.
 Polymorphism: They enable polymorphism, where objects of different concrete subclasses can
be treated uniformly through their common abstract base class, allowing for flexible and
extensible code.

Example:

from abc import ABC, abstractmethod

class Shape(ABC): # Abstract Base Class


@abstractmethod
def area(self):
pass # Abstract method, no implementation

@abstractmethod
def perimeter(self):
pass # Abstract method, no implementation

def describe(self): # Concrete method


print("This is a shape.")

class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius

def perimeter(self):
return 2 * 3.14 * self.radius

# shape_obj = Shape() # This would raise a TypeError


circle_obj = Circle(5)
print(f"Circle area: {circle_obj.area()}")
circle_obj.describe()

You might also like