Python inheritance

Inheritance is one of the OOP(Object Oriented Programming) Concept. It involves a parent and child class.

A class is created and its member functions are defined. This class is called base class or parent class. When you want a copy of base class, you can inherit it  and create a child class.

A child class is simply a replica of base class.

1)Here, a base class is created with name " customer"

class customer:

  def __init__(cust, fname, lname):

    cust.firstname = fname

    cust.lastname = lname

    def printfullname(cust):

    print(cust.firstname, cust.lastname)

#Use the customer class to create an object, and then execute the printfullname method:

x = customer("jeev", "anand")

x.printfullname()

 

2) A child class “Regularcustomer” is created.

#Creating a child class Regularcustomer

class Regularcustomer(customer):

  pass

# pass denotes this class doesnot have any definition.

3)The variables and member functions are included in child class “Regularcustomer”

#The child class access the base class function printfullname()

  y = Regularcustomer(“Jey” ,”anth”)

  y.printfullname()

 when you execute this program, you get the following output.

 


How to override the child class function:

If you want to override the child class function,add the following code.

class Regularcustomer(customer):

   def __init__(cust, fname,lname):

      customer. __int__(cust,fname,lname)

If you want to add new member functions, use super() method.

 class Regularcustomer(customer):

    def __init__(cust, fname,lname):

       super(). __init__(fname,lname)

 #Add a new property age

       cust.age=25

       z= regularcustomer(" raje " , " eswari " , 25)

when you a new member function, the code will be

class Regularcustomer(customer):

    def __init__(cust, fname,lname,age):

       super(). __init__(fname,lname)

       cust.currentage=age

def message(cust):

    print(“Happy birthday”,cust.fitstname,cust.lastname,” for the year of”,cust.currentage)

when you execute this,you get the following output.


This is the way of using inheritance in python is explained with simple example of customer and regular customer.



No comments:

Post a Comment