part6-3 Python 類和對象練習


練習:

1、編寫一個學生類,提供 name、age、gender、phone、address、email等屬性,為學生類提供帶所有成員變量的構造器,為學生類提供方法,用於描繪吃、喝、玩、睡等行為。
 1 class Student:  2     """描述學生的類"""
 3     def __init__(self, name, age, gender, phone, address, email):  4         """構造器函數"""
 5         self.name = name  6         self.age = age  7         self.gender = gender  8         self.phone = phone  9         self.address = address 10         self.email = email 11 
12     def eat(self, food): 13         """"""
14         print("%s正在吃%s" % (self.name, food)) 15 
16     def drink(self, drink): 17         """"""
18         print("%s正在喝%s" % (self.name, drink)) 19 
20     def play(self, sport, other): 21         """"""
22         print("我今年%s歲,正在和%s玩%s" % (self.age, other, sport)) 23 
24     def sleep(self): 25         """"""
26         print("%s正在%s睡覺" % (self.name, self.address)) 27 
28     def __repr__(self): 29         return 'Student(name=%s, age=%s, phone=%s, address=%s, email=%s)' % \ 30  (self.name, self.age, self.phone, self.address, self.email) 31 
32 if __name__ == '__main__': 33     stu = Student('Michael', 25, 201901, 10086, '成都', 'michael@163.com') 34     stu.eat('蘋果') 35     stu.drink('飲料') 36     stu.play('藍球', 'Stark') 37  stu.sleep() 38     print(stu) 39 
40 程序運行結果如下: 41 Michael正在吃蘋果 42 Michael正在喝飲料 43 我今年25歲,正在和Stark玩藍球 44 Michael正在成都睡覺 45 Student(name=Michael, age=25, phone=10086, address=成都, email=michael@163.com)

2、 利用前面定義的 Student 類,定義一個列表保存多個 Student 對象作為通訊錄數據。程序可通過 name、email、address 查詢,如果找不到數據,則進行友好提示。
 1 # 首先導入 Student 類,student 是文件名
 2 from student import Student  3 
 4 # 定義一個列表保存多個 Student 對象
 5 concacts = [Student('michael', 25, 201901, 10086, '成都', 'michael@163.com'),  6             Student('stark', 28, 201902, 10001, '重慶', 'stark@126.com'),  7             Student('tom', 31, 201903, 10087, '上海', 'tom@sina.com.cn'),  8             Student('jack', 27, 201904, 10081, '上海', 'jack@qq.com')]  9 
10 # 查詢 name
11 def find_by_name(name): 12     return [x for x in concacts if name in x.name] 13 
14 def find_by_email(email): 15     return [x for x in concacts if email in x.email] 16 
17 def find_by_address(address): 18     return [x for x in concacts if address in x.address] 19 
20 if __name__ == '__main__': 21     t = input('請輸入查找的方式,名字(n),Email(e),地址(a): ') 22     k = input('請輸入查找的關鍵字:') 23     if t == 'n': 24         print(find_by_name(k)) 25     elif t == 'e': 26         print(find_by_email(k)) 27     elif t == 'a': 28         print(find_by_address(k)) 29     else: 30         print('輸入有誤!') 31 
32 運行示例如下所示: 33 請輸入查找的方式,名字(n),Email(e),地址(a): a 34 請輸入查找的關鍵字:上海 35 [Student(name=tom, age=31, phone=10087, address=上海, email=tom@sina.com.cn), 36  Student(name=jack, age=27, phone=10081, address=上海, email=jack@qq.com)]

3、 定義代表二維坐標系上某個點的 Point 類(包括x、y兩個屬性),為該類提供一個方法用於計算兩個Point 之間的距離,再提供一個方法用於判斷三個Point 組成的三角形是鈍角、銳角還是直角三角形。
class Point: def __init__(self, x, y): self.x = x self.y = y def distance(self, other): """計算兩點之間的距離"""
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

    def judge_triangle(self, p1, p2): '''判斷3個點組成的三角形'''
        # 首先計算3條邊的距離
        self_p1 = self.distance(p1) self_p2 = self.distance(p2) p1_p2 = p1.distance(p2) # 如果 self_p1 的距離最大
        if self_p1 > self_p2 and self_p1 > p1_p2: if self_p1 > (self_p2 + p1_p2): print('不是三角形') else: print('鈍角三角形') if self_p1 ** 2 > (self_p2 ** 2 + p1_p2 ** 2) \ else print('銳角三角形') if self_p1 ** 2 < (self_p2 ** 2 + p1_p2 ** 2) \ else print('直角三角形') # 如果 self_p2 的距離最大
        if self_p2 > self_p1 and self_p2 > p1_p2: if self_p2 > (self_p1 + p1_p2): print('不是三角形') else: print('鈍角三角形') if self_p2 ** 2 > (self_p1 ** 2 + p1_p2 ** 2) \ else print('銳角三形') if self_p2 ** 2 < (self_p1 ** 2 + p1_p2 ** 2) \ else print('直角三角形') # 如果 p1_p2 的距離最大
        if p1_p2 > self_p1 and p1_p2 > self_p2: if p1_p2 > (self_p1 + self_p2): print('不是三角形') else: print('鈍角三角形') if p1_p2 ** 2 > (self_p1 ** 2 + self_p2 ** 2) \ else print('銳角三角形') if p1_p2 ** 2 < (self_p1 ** 2 + self_p2 ** 2) \ else print('直角三角形') def __repr__(self): return 'Point(x=%s, y=%s)' % (self.x, self.y) if __name__ == '__main__': p1 = Point(1, 1) print(p1.distance(Point(2, 3))) p1.judge_triangle(Point(4, 5), Point(-8, 7)) 程序運行結果如下所示: 2.23606797749979 鈍角三角形

4、 定義代表三維笛卡爾坐標系上某個點的 Points 類(包含x、y、z三個屬性),為該類定義一個方法,可接收b、c、d 三個參數,用於計算當前點和b、c 組成的面與 b、c、d 組成的面之間的夾角。提示:cos(夾角)=(X·Y)/|X||Y|,其中 X=AB*BC,Y=BC*CD,X·Y 代表X與Y的點積,AB*BC 代表 AB 與 BC 的叉乘。
 1 import math  2 
 3 class Points:  4     '''描述點的類'''
 5     def __init__(self, x, y, z):  6         '''構造器'''
 7         self.x = x  8         self.y = y  9         self.z = z 10 
11     def __sub__(self, other): 12         '''為減法提供支持的方法'''
13         return Points((self.x - other.x), (self.y - other.y), (self.z - other.z)) 14 
15     def dot(self, other): 16         """點積,相乘后積相加"""
17         return (self.x * other.x) + (self.y * other.y) + (self.z * other.z) 18 
19     def cross(self, other): 20         """叉積"""
21         return Points((self.y*other.z-self.z*other.y), (self.z*other.x-self.x*other.z), (self.x*other.y-self.y*other.x)) 22 
23     def absolute(self): 24         return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5) 25 
26 if __name__ == '__main__': 27     points = list() 28     print('依次輸入4個點的 x y z(中間以空格分隔)') 29     for _ in range(4): 30         a = list(map(float, input().split())) 31  points.append(a) 32     a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3]) 33     X = (b - a).cross(c - b) 34     Y = (c - b).cross(d - c) 35     angle = math.acos(X.dot(Y) / (X.absolute() * Y.absolute())) 36     print("%.2f" % math.degrees(angle)) 37 
38 運行一次實例如下: 39 依次輸入4個點的 x y z(中間以空格分隔) 40 2.8 9.5 -12.4
41 4.9 23.5 14.2
42 -60.8 -100 200
43 200 -300 -1000
44 12.92

5、 定義交通工具、汽車、火車、飛機類,注意這些類的繼承關系,為這些類提供構造器。
 1 class TrafficTools:  2     def __init__(self, name):  3         self.name = name  4 
 5     def move(self, distance):  6         print("我移動了%s千米" % distance)  7 
 8 class Car(TrafficTools):  9     def __init__(self, name, color): 10         super(Car, self).__init__(name) 11         self.color = color 12 
13     def move(self, distance): 14         print("我是%s的%s車,在道路上移動了%s千米" % (self.color, self.name, distance)) 15 
16 class Train(TrafficTools): 17     def __init__(self, name, color): 18         super(Train, self).__init__(name) 19         self.color = color 20 
21     def move(self, distance): 22         print("我是%s的%s,在鐵軌上移動了%s千米" % (self.color, self.name, distance)) 23 
24 class Plain(TrafficTools): 25     def __init__(self, name, company): 26         super(Plain, self).__init__(name) 27         self.company = company 28 
29     def move(self, distance): 30         print("我是%s的%s飛機,在天空中飛了%s千米" % (self.company, self.name, distance)) 31 
32 if __name__ == '__main__': 33     c = Car('寶馬', '紅色') 34     c.move(100.33) 35 
36     t = Train('火車', '綠皮') 37     t.move(50) 38 
39     p = Plain('空客', '川航') 40     p.move(400) 41 
42 運行結果如下所示: 43 我是紅色的寶馬車,在道路上移動了100.33千米 44 我是綠皮的火車,在鐵軌上移動了50千米 45 我是川航的空客飛機,在天空中飛了400千米

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM