×

Html & Html5

The World's best Software Development Study Portal

Python Inheritance


Through inheritance we can define any class that inherits or that follow all the methods and properties of other class. We are having two classes over here which are as follows :-

  • Parent class :- Also known as base class from which the other class being inherited.
  • Child class:- That class which is being inherited from the Parent class.



create a parent class:-

class Manish:

def __init__(self, fname,mname, lname):

self.firstname = fname

self.middlename = mname

self.lastname = lname

def printname(self):

print(self.firstname, self.middlename, self.lastname)

x = Manish("Manish", "Singh","Bhakuni")

x.printname()






Output of this Program


inheritance.png

So here our Parent class is ready. .




create a child class:-

class Manish:

def __init__(self, fname,mname, lname):

self.firstname = fname

self.middlename = mname

self.lastname = lname

def printname(self):

print(self.firstname, self.middlename, self.lastname)

class Student(Manish):

pass

x = Manish("Manish", "Pooja","Nikita")

x.printname()






Output of this Program


inhritance.png

So here our child class is been ready by which we are having all values inherited in it from its parent class.




Add method

We can also add method welcome to the student class.
let's have an example :-


class Manish:

def __init__(self, fname,mname, lname):

self.firstname = fname

self.middlename = mname

self.lastname = lname

def printname(self):

print(self.firstname, self.middlename, self.lastname)

class Student(Manish):

def __init__(self, fname,mname, lname, year):

Manish.__init__(self, fname,mname, lname)

self.futureyear = year

def welcome(self):

print("Welcome", self.firstname,self.middlename, self.lastname, "to the future of", self.futureyear)

x = Student("Manish", "Singh", "Bhakuni", 2019)

x.welcome()






Output of this Program


inheritance.png

So here is how we have added the welcome method .



python training insitute| Best IT Training classes in Gurgaon | python training