Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Inheritance and Composition in Python
Next article icon

Inheritance and Composition in Python

Last Updated : 01 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite - Classes and Objects in Python

This article will compare and highlight the features of is-a relation and has-a relation in Python.

What is Inheritance (Is-A Relation)? 

It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all the properties from another class. The class from which the properties and functionalities are utilized is called the parent class (also called as Base Class). The class which uses the properties from another class is called as Child Class (also known as Derived class). Inheritance is also called an Is-A Relation. 

Inheritance - diagrammatic representation

In the figure above, classes are represented as boxes. The inheritance relationship is represented by an arrow pointing from Derived Class(Child Class) to Base Class(Parent Class). The extends keyword denotes that the Child Class is inherited or derived from Parent Class. 

Syntax :   

# Parent class  class Parent :                     # Constructor             # Variables of Parent class               # Methods             ...               ...      # Child class inheriting Parent class   class Child(Parent) :               # constructor of child class             # variables of child class             # methods of child class               ...               ...   

Example : 

Python3
# parent class class Parent:      # parent class method     def m1(self):         print('Parent Class Method called...')  # child class inheriting parent class class Child(Parent):      # child class constructor     def __init__(self):         print('Child Class object created...')      # child class method     def m2(self):         print('Child Class Method called...')   # creating object of child class obj = Child()  # calling parent class m1() method obj.m1()  # calling child class m2() method obj.m2() 

Output
Child Class object created...  Parent Class Method called...  Child Class Method called...    

What is Composition (Has-A Relation)? 

It is one of the fundamental concepts of Object-Oriented Programming. In this concept, we will describe a class that references to one or more objects of other classes as an Instance variable. Here, by using the class name or by creating the object we can access the members of one class inside another class. It enables creating complex types by combining objects of different classes. It means that a class Composite can contain an object of another class Component. This type of relationship is known as Has-A Relation.

composition - diagrammatic representation

 In the above figure Classes are represented as boxes with the class name Composite and Component representing Has-A relation between both of them.   

class A :          # variables of class A        # methods of class A        ...        ...    class B :         # by using "obj" we can access member's of class A.        obj = A()          # variables of class B        # methods of class B                ...        ...  

Example : 

Python3
class Component:     # composite class constructor     def __init__(self):         print('Component class object created...')      # composite class instance method     def m1(self):         print('Component class m1() method executed...')   class Composite:      # composite class constructor     def __init__(self):          # creating object of component class         self.obj1 = Component()                  print('Composite class object also created...')       # composite class instance method     def m2(self):                print('Composite class m2() method executed...')          # calling m1() method of component class         self.obj1.m1()   # creating object of composite class obj2 = Composite()  # calling m2() method of composite class obj2.m2() 

Output
Component class object created...  Composite class object also created...  Composite class m2() method executed...  Component class m1() method executed...    

Explanation:

  • In the above example, we created two classes Composite and Component to show the Has-A Relation among them.
  • In the Component class, we have one constructor and an instance method m1().
  • Similarly, in Composite class, we have one constructor in which we created an object of Component Class. Whenever we create an object of Composite Class, the object of the Component class is automatically created.
  • Now in m2() method of Composite class we are calling m1() method of Component Class using instance variable obj1 in which reference of Component Class is stored.
  • Now, whenever we call m2() method of Composite Class, automatically m1() method of Component Class will be called.

Composition vs Inheritance  

 It's big confusing among most of the people that both the concepts are pointing to Code Reusability then what is the difference b/w Inheritance and Composition and when to use Inheritance and when to use Composition? 

Inheritance is used where a class wants to derive the nature of parent class and then modify or extend the functionality of it. Inheritance will extend the functionality with extra features allows overriding of methods, but in the case of Composition, we can only use that class we can not modify or extend the functionality of it. It will not provide extra features. Thus, when one needs to use the class as it without any modification, the composition is recommended and when one needs to change the behavior of the method in another class, then inheritance is recommended.


Next Article
Inheritance and Composition in Python

R

ronilpatil
Improve
Article Tags :
  • Python
  • Python-Quizzes
  • python-oop-concepts
  • Python-OOP
Practice Tags :
  • python

Similar Reads

    Conditional Inheritance in Python
    It happens most of the time that given a condition we need to decide whether a particular class should inherit a class or not, for example given a person, if he/she is eligible for an admission in a university only then they should be a student otherwise they should not be a student. Let's consider
    3 min read
    Inheritance in Python
    Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
    7 min read
    Function Composition in Python
    Function composition is a powerful concept where two or more functions are combined in such a way that the output of one function becomes the input for the next. It allows for the creation of complex functionality from simple, reusable building blocks. This concept is widely used in functional progr
    6 min read
    Inheritance in Python | Set 2
    Prerequisite : basics of inheritance in Python, Inheritance, examples of object, issubclass and super There are 2 built-in functions in Python that are related to inheritance. They are: 1. isinstance(): It checks the type of an object. Its syntax is: isinstance(object_name, class_name) It would retu
    4 min read
    Inheritance in Python Inner Class
    A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
    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