Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Call the main() Function of an Imported Module in Python
Next article icon

How To Make a Subclass from a Super Class In Python

Last Updated : 23 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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
# super class class Base:     # constructor to initialize attributes     def __init__(self, name, roll, age):         self.name = name         self.roll = roll         self.age = age  # sub class class Sub(Base):     # constructor to initialize attributes of both Base and Sub class     def __init__(self, name, roll, age):         super().__init__(name, roll, age)      # method to display information     def display(self):         print(f" Name: {self.name}\n Roll: {self.roll}\n Age: {self.age}")  # creating an object of Sub class 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
# Superclass class Base:     def __init__(self, name, roll, age):         self.name = name         self.roll = roll         self.age = age  # Create a subclass using type.__new__ Sub = type("Sub", (Base,), {})  # Creating an object of the Subclass with data obj = Sub("Sonali", 58, 24)  # Displaying information 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  # Superclass using namedtuple Base = namedtuple('Base', ['name', 'roll', 'age'])  # Subclass with additional attribute class Sub(Base):     def __new__(cls, name, roll, age, extra):         obj = super(Sub, cls).__new__(cls, name, roll, age)         obj.extra = extra         return obj  # Creating an object of the Subclass with data obj = Sub("Sonali", 58, 24, "Additional Info")  # Displaying information 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

Next Article
How to Call the main() Function of an Imported Module in Python

H

harshasi1eet
Improve
Article Tags :
  • Python
  • Python Programs
  • python-oop-concepts
Practice Tags :
  • python

Similar Reads

  • How to Change Class Attributes By Reference in Python
    We have the problem of how to change class attributes by reference in Python, we will see in this article how can we change the class attributes by reference in Python. What is Class Attributes?Class attributes are typically defined outside of any method within a class and are shared among all insta
    3 min read
  • How Can I Make One Python File Run Another File?
    In Python programming, there often arises the need to execute one Python file from within another. This could be for modularity, reusability, or simply for the sake of organization. In this article, we will explore different approaches to achieve this task, each with its advantages and use cases. Ma
    2 min read
  • What Does Super().__Init__(*Args, **Kwargs) Do in Python?
    In Python, super().__init__(*args, **kwargs) is like asking the parent class to set itself up before adding specific details in the child class. It ensures that when creating an object of the child class, both the parent and child class attributes are initialized correctly. It's a way of saying, In
    4 min read
  • How to Call the main() Function of an Imported Module in Python
    We are given an imported module and our task is to call the main() function of that module after importing it in Python. In this article, we will see how to call the main() of an imported module in Python. Call the main() Function of an Imported Module in PythonBelow, are the code methods of how to
    3 min read
  • How to Call a Method on a Class Without Instantiating it in Python?
    In Python programming, classes and methods are like building blocks for organizing our code and making it efficient. Usually, we create instances of classes to access their parts—attributes and methods. But sometimes, we might want to use a class or its methods without actually creating an instance.
    3 min read
  • Python Program to Get the Class Name of an Instance
    In this article, we will see How To Get a Class Name of a class instance. For getting the class name of an instance, we have the following 4 methods that are listed below: Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.Use the type() function and
    4 min read
  • Run One Python Script From Another in Python
    In Python, we can run one file from another using the import statement for integrating functions or modules, exec() function for dynamic code execution, subprocess module for running a script as a separate process, or os.system() function for executing a command to run another Python file within the
    5 min read
  • Private Attributes in a Python Class
    In Python, encapsulation is a key principle of object-oriented programming (OOP), allowing you to restrict access to certain attributes or methods within a class. Private attributes are one way to implement encapsulation by making variables accessible only within the class itself. In this article, w
    2 min read
  • Python Super() With __Init__() Method
    In object-oriented programming, inheritance plays a crucial role in creating a hierarchy of classes. Python, being an object-oriented language, provides a built-in function called super() that allows a child class to refer to its parent class. When it comes to initializing instances of classes, the
    4 min read
  • Python | Using variable outside and inside the class and method
    In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let's see, how to use and access these variables throughout the program. Variable defined outside the class: The variables that are defined outside the class can be accessed by any class or any me
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences