Friday, March 10, 2017

Classes and Objects Python

Tags

Following are Some Examples to illustrate the concept:

Code::
1.

class rectangle:
    def __init__(self,w,h):
        self.w=w
        self.h=h
   
    def area(self):
        self.area=self.w*self.h
        return self.area
   
    def perimeter(self):
        self.perimeter=2*(self.w+self.h)
        return self.perimeter
   
    def issquare(self):
        if(self.w is self.h):
            return True
        else:
            return False
   
    def getw(self):
        return self.w
   
    def geth(self):
        return self.h
   
r=rectangle(5,5)
print("Width:",r.getw(),"Height:",r.geth())
print("Area is:",r.area())
print("Perimeter is:",r.perimeter())
print("IsSquare:",r.issquare())

Output::
2.

class complex:
    def __init__ (self,a,b):
        self.r=a
        self.i=b
   
    def add(self,sec):
        r=complex(0,0)
        r.r=self.r+sec.r
        r.i=self.i+sec.i
        return r
       
    def sub(self,sec):
        r=complex(0,0)
        r.r=self.r-sec.r
        r.i=self.i-sec.i
        return r
   
    def mul(self,sec):
        r=complex(0,0)
        r.r=self.r*sec.r
        r.i=self.i*sec.i
        return r
   
    def div(self,sec):
        r=complex(0,0)
        r.r=self.r/sec.r
        r.i=self.i/sec.i
        return r
   
    def __str__ (self):
        return(str(self.r)+"+"+str(self.i)+"i")
   
c1=complex(2,3)
c2=complex(3,1)
print("Addition is:",c1.add(c2))
print("Subtraction is:",c1.sub(c2))
print("Multiplication is:",c1.mul(c2))

print("Division is:",c1.div(c2))

Output::