How to create polymorphism in python ?

Polymorphism
This is programming system where the same command has different mean based on the number of
input type of input or the object which command belong.

 

In this program create result of student and check student fail or pass
where we take input to user ‘student name’,’roll no’,’marks in first subject’,’marks in second subject’,’marks in third subject’
if we not pass any single argument than program ask for that input

All Method working
__init__(self):
in this method pass all argument of this class.
we pass argument==None and check in if block ‘if(argument==None)’ then we take input by user at run time
this condition only work that time when user not pass argument value in class object.

isPass(self):
in this method we check student pass in all subject or not.

total(self):
in this method find out the sum of all subject marks.

__str__(self):
in this method we return all value as output,if any variable is not string
then we use str( ) keyword and put the variable in side the ( ) of str .

class Result:
    def __init__(self,rollno=None,name=None,physics=None,chemistry=None,math=None):
        if(rollno==None):
            self.rollno=int(input("Enter Roll No="))
        else:
            self.rollno=rollno
        if(name==None):
            self.name=input("Enter Name=")
        else:
            self.name=name
        if(physics==None):
            self.physics=int(input("Enter Marks in physics="))
        else:
            self.physics=physics
        if(chemistry==None):
            self.chemistry=int(input("Enter Marks in Chemistry="))
        else:
            self.chemistry=chemistry
        if(math==None):
            self.math=int(input("Enter Marks in Math="))
        else:
            self.math=math
    def isPassed(self):
       if((self.math)>=40 and(self.chemistry)>=40 and(self.physics)>=40):
           return True
       else:
           return False
    def total(self):
        return self.physics+ self.chemistry + self.math
    def percent(self):
        return self.total()/3
    def __str__(self):
        return  "Name="+self.name+", Roll No="+str(self.rollno)+", Physics="+str(self.physics)+", Chemistry="+str(self.chemistry)+", Math="+str(self.math)+", Total="+str(self.total())+", Status="+str(self.isPassed()) + str(self.percent())                                                 
res=Result(1,"abhay",34,40)
print(res)    

Output of above Program

Enter Marks in Math=87
Name=abhay, Roll No=1, Physics=45, Chemistry=60, Math=87, Total=192, Status=Pass, Percentage=64.0

Leave a Reply