Inheritance is a fundamental idea in object-oriented programming (OOP) languages. By deriving a class from another class, you can use this mechanism to build a hierarchy of classes that share a set of properties and methods.
Class BaseClass:
Body
Class DerivedClass(BaseClass):
Body
class Person(object):
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name
# To check if this person is an employee
def isStudent(self):
return False
# Inherited or Subclass (Note Person in bracket)
class Student(Person):
# Here we return true
def isStudent(self):
return True
# Driver code
obj = Person("Mayank") # An Object of Person
print(obj.getName(), obj.isStudent())
obj = Student("Shital") # An Object of Employee
print(obj.getName(), obj.isStudent())
Mayank False
Shital True
You might occasionally need to use the functions or properties of the parent class while working in a child class. The dot. operator can be used to access the elements of a parent class.
Example:
Parent.variableName
We have a straightforward example to illustrate this below:
class Parent:
var1 = 1
def func1(self):
# do something here
class Child(Parent):
var2 = 2
def func2(self):
# do something here too
# time to use var1 from 'Parent'
myVar = Parent.var1 + 10
return myVar
Note: also read about Destructors in Python
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…