جلسه سی ام
حل تمرین شی گرایی
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<xmp>مثال 1: کلاس اشکال و محاسبه محیط و مساحت بوسیله متود های کلاس class diagram : def __init__(self , lenght ,width ) : self.lenght = lenght self.width = width def enviroment (self) : p = 2 * (self.lenght + self.width) return p def area (self) : s = self.lenght * self.width return s square = diagram( 5 , 5 ) rectangle = diagram( 10 , 6 ) print(f'enviroment of square = {square.enviroment()}') print(f'area of square = {square.area()}') print(f'enviroment of rectangle = {rectangle.enviroment()}') print(f'area of rectangle = {rectangle.area()}')</xmp> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<xmp>مثال 2: کلاس اعداد اول. class aval : def __init__ (self , first , end): self.first = first self.end = end def avaal (self) : my_list =[] temp = False for i in range(self.first , self.end): for x in range (2 , i): if i % x == 0 : temp = False break else: temp = True if temp == True: my_list.append(i) return my_list aval1 = aval(15 , 200) print(f'adad avl bein 15 ta 80 = {aval1.avaal()}')</xmp> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<xmp>مثال 3:کلاس توان class Power : def __init__ (self , number , power ) : self.number = number self.power = power def calcatulate (self): result = self.number ** self.power return result number = int(input("enter a number = ")) power = int (input("enter power for number = ")) Power1 = Power(number , power) print(f' {number}**{power} = {Power1.calcatulate()}')</xmp> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<xmp>مثال 4:کلاس میانگین و انحراف معیار اعداد class num_list : def __init__(self , mylist ) : self.mylist = mylist def Average(self) : ave = sum(self.mylist)/len(self.mylist) return ave def varians(self) : sum = 0 ave = self.Average() for x in self.mylist : var = (x - ave) **2 sum += var var = var / len(self.mylist) return var mylist = [1 , 2 , 3 , 4 , 5] num_list1 = num_list(mylist) print(f' average = {num_list1.Average()}') print(f'varianse = {num_list1.varians()}')</xmp> |