- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Introduction to Classes and Inheritance in Python
Object-oriented programming creates reusable patterns of code to prevent code redundancy in projects. One way that recyclable code is created is through inheritance, when one subclass leverages code from another base class.
Inheritance is when a class uses code written within another class.
Classes called child classes or subclasses inherit methods and variables from parent classes or base classes.
Because the Child subclass is inheriting from the Parent base class, the Child class can reuse the code of Parent, allowing the programmer to use fewer lines of code and decrease redundancy.
Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name −
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
class Parent: # define parent class parentAttr = 100 def __init__(self): print "Calling parent constructor" def parentMethod(self): print 'Calling parent method' def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print "Parent attribute :", Parent.parentAttr class Child(Parent): # define child class def __init__(self): print "Calling child constructor" def childMethod(self): print 'Calling child method' c = Child() # instance of child c.childMethod() # child calls its method c.parentMethod() # calls parent's method c.setAttr(200) # again call parent's method c.getAttr() # again call parent's method
When the above code is executed, it produces the following result
Calling child constructor Calling child method Calling parent method Parent attribute :200
- Explain Inheritance vs Instantiation for Python classes.
- Explain sub-classes and inheritance in ES6
- How we can extend multiple Python classes in inheritance?
- How does class variables function in multi-inheritance Python classes?
- Explain the usage of Classes and the Benefits of Inheritance in Swift
- Introduction to Data Science in Python
- Inheritance in Python
- Introduction To Machine Learning using Python
- Introduction to Python for Data Science
- Class Inheritance in Python
- How to define classes in Python?
- How to organize Python classes in modules and/or packages
- Introduction to Kivy; A Cross-platform Python Framework
- Creating Classes in Python