How To Make a Subclass from a Super Class In Python
Last Updated :
23 Feb, 2024
In Python, you can create a subclass from a superclass using the class keyword, and by specifying the superclass in parentheses after the subclass name. The subclass inherits attributes and behaviors from the superclass, allowing you to extend or modify its functionality while reusing the existing code. This process is known as inheritance and supports the principles of object-oriented programming. In this article, we are going to learn how to make a Subclass from a Super Class in Python using three approaches.
Make a Subclass from a Super Class In Python
Below are the possible approaches to making a subclass from a superclass in Python
- Using the class keyword and super() method
- Using type.__new__ method
- Using collections.namedtuple
Subclass from a Super Class Using class keyword and super() method
In this approach, a subclass Sub is created from the superclass Base using the class keyword in Python. The subclass inherits attributes from the superclass through the super() function, enabling the reuse and extension of code.
Python3
class Base:
def __init__( self , name, roll, age):
self .name = name
self .roll = roll
self .age = age
class Sub(Base):
def __init__( self , name, roll, age):
super ().__init__(name, roll, age)
def display( self ):
print (f " Name: {self.name}\n Roll: {self.roll}\n Age: {self.age}" )
obj = Sub( "Sonali" , 58 , 24 )
obj.display()
|
Output
Name: Sonali
Roll: 58
Age: 24
Subclass From a Super Class Using type.__new__ method
In this approach, the type.__new__ method is used to create a subclass Sub from the superclass Base. The third argument, {}, can be used to provide additional attributes or methods to the subclass.
Python3
class Base:
def __init__( self , name, roll, age):
self .name = name
self .roll = roll
self .age = age
Sub = type ( "Sub" , (Base,), {})
obj = Sub( "Sonali" , 58 , 24 )
print (f " Name: {obj.name}\n Roll: {obj.roll}\n Age: {obj.age}" )
|
Output
Name: Sonali
Roll: 58
Age: 24
Subclass from a Super Class Using collections.namedtuple
In this approach, a subclass Sub is created from the superclass Base using a namedtuple. The __new__ method is overridden in the subclass to include an additional attribute and an object obj is instantiated with data.
Python3
from collections import namedtuple
Base = namedtuple( 'Base' , [ 'name' , 'roll' , 'age' ])
class Sub(Base):
def __new__( cls , name, roll, age, extra):
obj = super (Sub, cls ).__new__( cls , name, roll, age)
obj.extra = extra
return obj
obj = Sub( "Sonali" , 58 , 24 , "Additional Info" )
print (f " Name: {obj.name}\n Roll: {obj.roll}\n Age: {obj.age}\n Extra: {obj.extra}" )
|
Output
Name: Sonali
Roll: 58
Age: 24
Extra: Additional Info
Share your thoughts in the comments
Please Login to comment...