Example 1
#create a class for a circle
class mycircle:
#private variable
__pi=22/7
def set_radious(self,r):
self.__r=r
def get_radious(self):
return self.__r
#constructor
def __init__(self,r):
self.set_radious(r)
#function to return area of a circle
def get_area(self):
return self.__r*self.__r*(self.__pi)
#function to return circumferences
def get_circumference(self):
return 2*self.__pi*self.__r
def __str__(self):
return "Circle radous:" + str(self.get_radious()) + " Area:"+ str(self.get_area()) + " Circumference: " +str(self.get_circumference())
#end of class
#main program
#create object and return string to variable x
x=mycircle(7)
print(x)
Output
Circle radous:7 Area:154.0 Circumference: 44.0
Example 2
#create a class for rectangle
class myRect:
def set_width(self,w):
self.w=w
def set_height(self,h):
self.h=h
def get_width(self):
return self.w
def get_height(self):
return self.h
def __init__(self,w,h):
self.set_width(w)
self.set_height(h)
def get_area(self):
return self.w * self.h
def get_circumference(self):
return 2*(self.w+self.h)
def __str__(self):
return "Rectangle Area:"+ str(self.get_area()) + " Circumference: " +str(self.get_circumference())
#main program
x=myRect(4,2)
print(x)
Output
Rectangle Area:8 Circumference: 12
#create a class for a circle
class mycircle:
#private variable
__pi=22/7
def set_radious(self,r):
self.__r=r
def get_radious(self):
return self.__r
#constructor
def __init__(self,r):
self.set_radious(r)
#function to return area of a circle
def get_area(self):
return self.__r*self.__r*(self.__pi)
#function to return circumferences
def get_circumference(self):
return 2*self.__pi*self.__r
def __str__(self):
return "Circle radous:" + str(self.get_radious()) + " Area:"+ str(self.get_area()) + " Circumference: " +str(self.get_circumference())
#end of class
#main program
#create object and return string to variable x
x=mycircle(7)
print(x)
Output
Circle radous:7 Area:154.0 Circumference: 44.0
Example 2
#create a class for rectangle
class myRect:
def set_width(self,w):
self.w=w
def set_height(self,h):
self.h=h
def get_width(self):
return self.w
def get_height(self):
return self.h
def __init__(self,w,h):
self.set_width(w)
self.set_height(h)
def get_area(self):
return self.w * self.h
def get_circumference(self):
return 2*(self.w+self.h)
def __str__(self):
return "Rectangle Area:"+ str(self.get_area()) + " Circumference: " +str(self.get_circumference())
#main program
x=myRect(4,2)
print(x)
Output
Rectangle Area:8 Circumference: 12
No comments:
Post a Comment