

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How does class inheritance work in Python?
Inheritance in classes
Instead of defining a class afresh, we can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and we can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.
Syntax
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
Example
#!/usr/bin/python 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
Output
When the above code is executed, it produces the following result −
Calling child constructor Calling child method Calling parent method Parent attribute : 200
- Related Questions & Answers
- How does Inheritance work in Ruby?
- How does Python's super() work with multiple inheritance?
- How does class variables function in multi-inheritance Python classes?
- How does nested character class subtraction work in Python?
- Class Inheritance in Python
- Does Python support multiple inheritance?
- How does Python while loop work?
- How does mkdir -p work in Python?
- How does garbage collection work in Python?
- How does issubclass() function work in Python?
- How does isinstance() function work in Python?
- How does Overloading Operators work in Python?
- How does ++ and -- operators work in Python?
- How does tuple comparison work in Python?
- How does Python dictionary keys() Method work?
Advertisements