--- title: Class 程式碼 - 資訊之芽 2023 Python 語法班 description: Sean 韋詠祥 / 2023-05-07 14:20 --- # Class 程式碼 > 資訊之芽 2023 Python 語法班 > Author: Sean 韋詠祥 > Slide: https://hackmd.io/@Sean64/py-class 逐個複製太麻煩了,整理出來方便使用 [ToC] ## 如果我們想要紀錄.... ```python speaker1_name = 'Sean Wei' speaker1_birthday = 'June' speaker1_skills = ['Cybersecurity', 'Diving'] speaker2_name = 'William Mou' speaker2_birthday = 'October' speaker2_skills = ['Photography', 'Supercomputing'] speaker3_name = 'Sirius Koan' speaker3_birthday = 'July' speaker3_skills = ['Softball', 'Mail'] ``` ### 透過 dict 化簡 ```python speaker1 = { 'name': 'Sean Wei', 'birthday': 'June', 'skills': ['Cybersecurity', 'Diving'] } speaker2 = { 'name': 'William Mou', 'birthday': 'October', 'skills': ['Photography', 'Supercomputing'] } speaker3 = { 'name': 'Sirius Koan', 'birthday': 'July', 'skills': ['Softball', 'Mail'] } ``` --- ## 如何使用 Class ```python class Speaker: pass speaker1.name = 'Sean Wei' speaker1.birthday = 'June' speaker1.skills = ['Cybersecurity', 'Diving'] speaker2.name = 'William Mou' speaker2.birthday = 'October' speaker2.skills = ['Photography', 'Supercomputing'] speaker3.name = 'Sirius Koan' speaker3.birthday = 'July' speaker3.skills = ['Softball', 'Mail'] ``` ### 正確的寫法 ```python class Speaker: def __init__(self, name, birthday, skills): self.name = name self.birthday = birthday self.skills = skills speaker1 = Speaker('Sean Wei', 'June', ['Cybersecurity', 'Diving']) speaker2 = Speaker('William Mou', 'October', ['Photography', 'Supercomputing']) speaker3 = Speaker('Sirius Koan', 'July', ['Softball', 'Mail']) ``` ### 課堂練習(一) ```python class Speaker: def __init__(self, name, birthday, skills): self.name = name self.birthday = birthday self.skills = skills def learn(self, teacher): print(f'{self=}, {self.skills=}') print(f'{teacher=}, {teacher.skills=}') # Write your code here speaker1 = Speaker('Sean Wei', 'June', ['Cybersecurity', 'Diving']) speaker2 = Speaker('William Mou', 'October', ['Photography', 'Supercomputing']) speaker3 = Speaker('Sirius Koan', 'July', ['Softball', 'Mail']) speaker1.learn(speaker2) ``` --- ## 繼承 ```python class Student: def __init__(self, name, age, student_id): self.name = name self.age = age self.student_id = student_id def say_hi(): print(f'Hello, I am {name}!') class Employee: def __init__(self, name, age, employee_id): self.name = name self.age = age self.employee_id = employee_id def say_hi(): print(f'Hello, I am {name}!') ``` ### 抽取重複部分 ```python class Person: def __init__(self, name, age): self.name = name self.age = age def say_hi(): print(f'Hello, I am {name}!') class Student(Person): def __init__(self, name, age, student_id): super().__init__(name, age) self.student_id = student_id class Employee(Person): def __init__(self, name, age, employee_id): super().__init__(name, age) self.employee_id = employee_id ``` ### 多層繼承的 super() ```python class First: def __init__(self): print('Initializing first class') # super().__init__() # no need class Second(First): def __init__(self): print('Initializing second class') super().__init__() class Third(Second): def __init__(self): print('Initializing third class') super().__init__() foo = Third() ``` ### 對於繼承多個類別的 super() 呢? ```python class Foo: def __init__(self): print('Initializing foo class') super().__init__() # note here class Bar: def __init__(self): print('Initializing bar class') # super().__init__() # no need class Test(Foo, Bar): def __init__(self): print('Initializing test class') super().__init__() baz = Test() ``` --- ## attribute 層級比較 ```python class Phone: pwd = '0000' foo = Phone() bar = Phone() print(f'{Phone.pwd=}, {foo.pwd=}, {bar.pwd=}') ``` --- ## 為什麼我的 list 不乖 ```python class Person: skills = [] def learn(self, skill): self.skills.append(skill) sean = Person() sean.learn('Cybersecurity') sean.learn('Diving') print(f'{sean.skills=}') mou = Person() mou.learn('Photography') mou.learn('Supercomputing') print(f'{mou.skills=}') ``` ### 正確寫法 ```python class Person: def __init__(self): # creates a new empty list for each person self.skills = [] def learn(self, skill): self.skills.append(skill) sean = Person() sean.learn('Cybersecurity') sean.learn('Diving') print(f'{sean.skills=}') mou = Person() mou.learn('Photography') mou.learn('Supercomputing') print(f'{mou.skills=}') ``` --- ## 魔術方法 ```python class Food: def __init__(self, price, calorie): self.price = price # Unit: NTD self.calorie = calorie # Unit: kcal chicken_nuggets = Food(65, 260) french_fries = Food(65, 530) oreo_flurry = Food(55, 360) corn_soup = Food(40, 90) ``` ### 印出價格、熱量 ```python class Food: def __init__(self, price, calorie): self.price = price # Unit: NTD self.calorie = calorie # Unit: kcal def __str__(self): return 'price and calorie is xxx' # 小練習 def __add__(self, other): price = 0 # 請完成 calorie = 0 # 請完成 mixture = Food(price, calorie) return mixture chicken_nuggets = Food(65, 260) french_fries = Food(65, 530) oreo_flurry = Food(55, 360) corn_soup = Food(40, 90) oreo_nuggets = oreo_flurry + chicken_nuggets print(oreo_nuggets) # price = 120 NTD, calorie = 620 kcal ``` ### 課堂練習(二) ```python class Food: # ... def __mul__(self, num): pass # 計算 num 份食物的價格、熱量 def __truediv__(self, num): pass # 平分給 num 個人後每份長怎樣 def __eq__(self, other): pass # 比較「💲價格」是否相同,暫時無視熱量 def __ne__(self, other): pass # (optional) 比較「💲價格」是否不同 def __gt__(self, other): pass # 比較「🔥熱量」是否更高 def __lt__(self, other): pass # (optional) 比較「🔥熱量」是否更低 def __ge__(self, other): pass # (optional) 比較「🔥熱量」是否更高或相同 def __le__(self, other): pass # (optional) 比較「🔥熱量」是否更低或相同 chicken_nuggets = Food(65, 260) french_fries = Food(65, 530) oreo_flurry = Food(55, 360) corn_soup = Food(40, 90) print(oreo_flurry * 5) # 五杯冰炫風多少錢 print(chicken_nuggets / 6) # 每塊麥克雞塊熱量多高 print(french_fries + corn_soup > oreo_flurry) # 薯條 + 玉米濃湯 > 冰炫風 ``` --- 結束! 感謝各位 owo// BTW, SITCON 夏令營準備要開始報名了 https://www.instagram.com/p/Crs2yM3hlrW/ 歡迎揪校內有興趣的同學抱團參加 回去有空可以看看上一屆的影片 {%youtube oAtiOrpj6DQ %} > 資訊之芽 2023 Python 語法班 > Author: Sean 韋詠祥 > Slide: https://hackmd.io/@Sean64/py-class <style> .markdown-body hr { background-color: #77B55A; } </style>