Create a Python Subclass
In Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without having to rewrite common functionality. To create a subclass in Python, you define a new class and specify the superclass in parentheses after the class name.
Below is the step-by-step guide to How to Create a Python Subclass.
Creating a simple subclass
Animal
is the base class with a __init__
method to initialize the name
attribute and a s
ound method. Dog
is a subclass Animal
that inherits from it. It overrides the s
ound method to provide a specific implementation for dogs.
Instances of both classes are created and we demonstrate how attributes and methods can be accessed.
class Animal:
def __init__(self, name):
# Storing the name of the animal
self.name = name
def sound(self):
# This method should be implemented by subclasses
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def sound(self):
# Dog-specific sound
return "Woof!"
# Creating instances
# Animal instance with generic name
a = Animal("Generic Animal")
# Dog instance with name 'Buddy'
d = Dog("Buddy")
# Accessing attributes and methods
print(a.name) # Output: Generic Animal
print(d.name) # Output: Buddy
print(d.sound()) # Output: Woof!
Output
Generic Animal Buddy Woof!
Syntax :
class SubclassName(BaseClassName):
# Class attributes and methods for the subclass
# ...
Adding additional attributes in the subclass
Shape
is the base class with an __init__
method to initialize the color
attribute and an abstract area
method.Circle
is a subclass of Shape
that extends it by adding a radius
attribute. It calls the superclass constructor using super()
to initialize the common attribute. The area
method is overridden in the Circle
subclass to provide a specific implementation for calculating the area of a circle.
class Shape:
def __init__(self, color):
# Storing the color of the shape
self.color = color
def area(self):
# This method should be implemented by subclasses
raise NotImplementedError("Subclasses must implement this method")
class Circle(Shape):
def __init__(self, color, radius):
# Initialize the parent class (Shape) with color
super().__init__(color)
# Storing the radius of the circle
self.radius = radius
def area(self):
# Circle-specific area calculation
return 3.14 * self.radius ** 2
# Creating instances
# Shape instance with color 'Red'
s = Shape("Red")
# Circle instance with color 'Blue' and radius 5
c = Circle("Blue", 5)
# Accessing attributes and methods
print(s.color) # Output: Red
print(c.color) # Output: Blue
print(c.radius) # Output: 5
print(c.area()) # Output: 78.5
Output
Red Blue 5 78.5