Python- Classes and Object

Class.py


#!/usr/bin/Python

class Calculator:
    def __init__(self,x,y):
              self.a=x
              self.b=y

    def add(self):
          return self.a+self.b

    def mul(self):
        return self.a*self.b


p=int(raw_input("Enter First value"))
q=int(raw_input("Enter Second value"))


obj=Calculator(p,q)

print'a+b= %d'%obj.add()
print'a*b=%d'%obj.mul()




Inheritance

#!/usr/bin/Python

class Calculator:
    def __init__(self,x,y):
              self.a=x
              self.b=y

    def add(self):
          return self.a+self.b

    def mul(self):
        return self.a*self.b




class calc2(Calculator):
           def power(self):
                   return pow(self.a,self.b)




p=int(raw_input("Enter First value"))
q=int(raw_input("Enter Second value"))

obj2=calc2(p,q)

print'a power b=%d'%obj2.power()

#Since child
print'a+b= %d'%obj2.add()
print'a*b= %d'%obj2.mul()

print'value of a = %d'%obj2.a
print'value of b = %d'%obj2.b


Reactions: