Multiple inheritances in python

Multiple inheritances:

  • Multiple inheritances have a number of base classes and one derived class.
  • It means the numbers of base classes are derived from one derived class.

Syntax:

  1. class a

              //Base class1

    class b

              //Base class2

    class c:public a,public b

              //Derived class

    //Object creation

    Object_name=Derived_class_name();

    object_name.function_name(parameter_list);

Example:

  1. #Multiple inheritance

    class bank:

        def pin_set(self):

            lst=[1111,1234,2222]

            print("\tWelcome to XXX bank")

            return lst

    class getvalue:

        def get_data(self):

            pin=int(input("Enter pin number:"))

            return pin

    class pin_validation(bank,getvalue):

        def verification(self,pin,lst):

           # for i in lst:

            if pin in lst:

                print("Enter your choice:\n1.Cash widrawel\n2.Cash deposite\n3.Mini statement")

            else:

                print("Invalid pin")

    b=pin_validation()

    l=[]

    l=b.pin_set()

    p=b.get_data()

    b.verification(p,l)

Output:

If condition:

Else condition:

Share:

Multilevel inheritance in python

Multilevel inheritance:

  • Multilevel inheritance has derived from the class itself and derives the subclass further.
  • It means one base class derived from intermediate class, that intermediate class derived the derived class.

Syntax:
  1. class a:
             //Base class
    class b: class a
             //Intermediate class

    class c: class b
              //Derived class
    Object creation:
    Object_name=last_class_name() ;
    object_name.function(parameter list);
Example:
  1. #Multi level inheritance

    class bank:

        def pin_set(self):

            lst=[1111,1234,2222]

            print("\tWelcome to XXX bank")

            return lst

    class getvalue(bank):

        def get_data(self):

            pin=int(input("Enter pin number:"))

            return pin

    class pin_validation(getvalue):

        def verification(self,pin,lst):

            if pin in lst:

                print("Enter your choice:\n1.Cash widrawel\n2.Cash deposite\n3.Mini statement")

            else:

                print("Invalid pin")

    b=pin_validation()

    l=[]

    l=b.pin_set()

    p=b.get_data()

    b.verification(p,l)

Output:

If condition:

Else condition:

Share:

Inheritance in python

Inheritance:

  • It is the process of joining two or more classes and we can access the values from both classes.

Types of Inheritance:

1) Single inheritance

2) Multilevel inheritance

3) Multiple inheritances

Benefits of inheritance:

  • Software re-usability
  • Information hiding
  • Code sharing

Syntax:

  1. class class_name1:

        #function definition

    class class_name2(class_name1):

        #function definition

    object_name=class_name(parameter_list)#Object creation

    object_name.function_name(parameter_list)#function calling

Example:

  1. #inheritance with constructor

    class employee:

        def __init__(self,id,name,depart,sal):

            self.id=id

            self.name=name

            self.depart=depart

            self.sal=sal

        def display(self):

            print("\tEmployee details")

            print("ID :",self.id)

            print("Name:",self.name)

            print("Department :",self.depart)

            print("Basic Salary : ",self.sal)

    class salary_cal(employee):

        def sal_cal(self)://access sal from base class

            if self.sal>=15000:

                self.sal+=5000

                print("Increased salary:5000")

                print("Net salary:",self.sal)

            elif self.sal>=1000 and self.sal<15000:

                self.sal+=3000

                print("Increased salary:3000")

                print("Net salary:",self.sal)

            else:

                self.sal+=1000

                print("Increased salary:1000")

                print("Net salary:",self.sal)

    id=input("Enter employee id:")

    name=input("Enter employee name:")

    depart=input("Enter employee department:")

    sal=int(input("Enter basic salary:"))

    #object creation

    emp=salary_cal(id,name,depart,sal)

    #emp=employee(id,name,depart,sal)

    emp.display()

    emp.sal_cal()

Output:

Share:

Single inheritance in python

 1) Single inheritance:

    • If one base class and one derived class in a program called  “Single inheritance”.
      Syntax:
      1. class a:
                  //Base class
        class b: public a
                  //Derived class
        Object creation:
        object_name=Derived_class_name();
        object_name.function(parameter list);
      Example:
      1. class employee:#base class

            def get_data(self):#All function should have the self keyword for joining other fun

                id=input("Enter employee id:")

                name=input("Enter employee name:")

                depart=input("Enter employee department:")

                sal=int(input("Enter basic salary:"))

                return id,name,depart,sal

            def display(self,id,name,depart,sal):

                print("\tEmployee details")

                print("ID :",id)

                print("Name:",name)

                print("Department :",depart)

                print("Basic Salary : ",sal)

        class salary_cal(employee):#derived class

            def sal_cal(self,sal):

                if sal>=15000:

                    sal+=5000

                    print("Increased salary:5000")

                    print("Net salary:",sal)

                elif sal>=1000 and sal<15000:

                    sal+=3000

                    print("Increased salary:3000")

                    print("Net salary:",sal)

                else:

                    sal+=1000

                    print("Increased salary:1000")

                    print("Net salary:",sal)

         

        #Object creation

        emp=salary_cal()

        empno,ename,deptno,sal=emp.get_data()

        emp.display(empno,ename,deptno,sal)

        emp.sal_cal(sal)

      Output:

    Share:

    Object and constructor in python

     Object:

    • An object is used to access the members of the class.
    • It simply said as the short name of the class.

    Constructor:

    • The constructor is used to initialize the variables and sharing the values to functions.
    • Further, it is mainly for object calls.
    • __init__ (double underscore) is the standard function name for initializing the values.
    • Self is not a keyword. It is just variable for connecting function value to constructor.
    • Self is used to pass a value into the function from constructor value.

    Syntax:
    1. import module_name#optional

      class class_name:

          def __init__(self,parameter_list):

              self.parameter_list=variable

          def function_name(self,list_of_patameters):

              #Statements

      object_name=class_name(parameter_list)#Parameter list based on constructor

      object_name.function_name(list_of_patameters)#Function calling through object

    Example program:

    1. class calculator:

          def __init__(self, x, y):

              self.x = x

              self.y = y

          def add(self):

              return self.x+self.y

          def sub(self):

              return self.x-self.y

          def mul(self):

              return self.x*self.y

          def div(self):

              return self.x/self.y

      x,y=input("Enter two values: ").split()

      c=calculator(int(x),int(y))

      print("Add value:",c.add())

      print("Sub value:",c.sub())

      print("Mul value:",c.mul())

      print("Div value:",c.div())

    Output:

    Share:

    Class in Python

    Introductions of Class:

    Class:
    • Class is used to hold data members and member function i.e. variables and functions.
    • It can be easily accessed anywhere and used to reduce the reusability of the code.
    • The class name is a user-defined word.
    For example,
    • Let’s take student,
    • Student properties are all called variables and student performance or student-related calculations(i.e. student result based on total and it may be pass or fail) is called as a function.
    Where,
    The student is a class.
    Student properties (variables) : Roll_num,name,age,ect.
    Student behaviours(function)  : total,average,result,fees details ect.
    Note:
    • If one or more variables declared within the class, called data members.
    • If one or more functions declared within the class, called member function.
    Syntax:
    1. import module_name#optional

      class class_name:

          def function_name(list_of_patameters):

              #Statements

          function_name(list_of_patameters)#Function calling

    Example program:

    1. class calculator:

          def add(x,y):

              return x+y

          def sub(x,y):

              return x-y

          def mul(x,y):

              return x*y

          def div(x,y):

              return x/y

          a,b=input("Enter two values: ").split()

          print("Add value:",add(int(a),int(b)))

          print("Sub value:",sub(int(a),int(b)))

          print("Mul value:",mul(int(a),int(b)))

          print("Div value:",div(int(a),int(b)))

    Output:

    Share:

    OOPs concept in python

     What is OOPs?

    • OOPS, the standard form is Object Oriented Programming Structure.
    • It is one of the ways of solving complex problems into smaller problems by using objects.
    • Before using OOPS, programs were written in a procedural language i.e. C language, they were nothing but a long list of instructions.

    Problems in C and overcome by OOPS:

    • If declare global variable then all function known that value because of the global variable is public so anyone can access i.e. here not possible the particular function only knowns the global value and data are not secure.
    • But, in the oops concept of having and managing objects and classes in java, the program key building block is Data. Therefore, secure data is tightly using access specifiers, classes, encapsulation, and so on.

    Uses of oops or why it used?

    • Reducing program lines.
    • Data secure.
    • Easy way to find errors.
    • Execution speed is fast.
    Features of oops in Python:

    • Class
    • Object
    • Constructor
    • Inheritance
    • Polymorphism
    • Overloading
    • Operator overloading
    • Exception handling

    Share:

    Create and import custom module in python

    Create and import custom module in python:

    • If create a custom module to import this module in another module, it should have function definition only.
    • File inclusion must be import keyword with the name of the created custom module.

    Save the program as a calculation.c

    1. def sqr(n):

          return n*n

      def cube(n):

          return n*n*n

    Created another program Example.py for file inclusion:

    1. import calculation

      x=int(input("Enter a value to find square value:"))

      print("%d square value is:%d"%(x,calculation.sqr(x)))

      y=int(input("Enter a value to find cube value:"))

      print("%d cube value is:%d"%(y,calculation.cube(y)))

    Output:

    Share:

    Read,write and append program in python

    Example program for reading, write and append:

    #Write functions to create a text file called student.txt to store few student details in a list of values

    #like enrollment number, name, gender, standard, and section. Also, write functions for the following

    #A. Append

    #S. Search

    #D.Display

    #E.Exit

     Program:

    1. def CREATE():

          f=open("D:\\KURSHITHA\\Notepad\\student.det","w")

          ch=1

          while ch:

              roll=int(input("Enter Roll Number:"))

              name=input("Enter name:")

              gen=input("Enter gender:")

              std=int(input("Enter std:"))

              sec=input("Enter Section:")

              rec=str(roll)+" "+name+" "+gen+" "+str(std)+" "+sec

              f.write(rec)

              f.write('\n')

              ch=int(input("Any more records (1 or 0 ):"))

          f.close()

       

      def APPEND():

          f=open("D:\\KURSHITHA\\Notepad\\student.det","a")

          ch=1

          while ch:

              roll=int(input("Enter Roll Number:"))

              name=input("Enter name:")

              gen=input("Enter gender:")

              std=int(input("Enter std:"))

              sec=input("Enter Section:")

              rec=str(roll)+" "+name+" "+gen+" "+str(std)+" "+sec

              f.write(rec)

              f.write('\n')

              ch=int(input("Any more records (1 or 0 ):"))

          f.close()

       

      def PRINT():

          f=open("D:\\KURSHITHA\\Notepad\\student.det","r")

          s=" "

          print("Roll  Name      Gender STD Section:")

          while s:

              s=f.readline()

              s=s.rstrip("\n")

              a=s.split(" ")

              for i in a:

                  print(i,end='\t')

              print()

          f.close()

       

      def SEARCH():

          f=open("D:\\KURSHITHA\\Notepad\\student.det","r")

          s=" "

          flag=0

          sroll=input("Enter the searching roll number:")

          while s:

              s=f.readline()

              if sroll in s:

                  print("Searching record details:",s)

                  flag+=1

          if flag==0:

              print("searching record not found")

          f.close()

       

      CREATE()#invoke create function

      while True:

          print("A. Append\nS. Search\nD. Display\nE. Exit")

          ch=input("Enter Your choice:")

          if ch in 'Aa':

              APPEND()

          elif ch in 'sS':

              SEARCH()

          elif ch in 'dD':

              PRINT()

          elif ch in 'eE':

              break

          else:

              print("Invalid choice")

    Output:

    Before running the program:

    After running the program:




    Share:

    Recent Posts

    Service Support

    Need our help to Learn or Post New Concepts Contact me