Python 物件導向程式設計(OOP)的基礎
物件導向程式設計(OOP)是 Python 的核心設計之一。透過(Class)、(Object)、繼承(Inheritance)、封裝(Encapsulation)、多態(Polymorphism)等特性,OOP 能幫助我們設計更具模組化、可重用性與維護性的程式碼。本篇將帶您全面了解 Python OOP 的基礎概念,並透過實例講解如何應用於真實世界的開發中。
本篇主要使用Class、Object、Inheritance、Polymorphism以及Magic Method作為範例。
- 創建一個名為 Person 的類別,包含名字和年齡屬性,以及一個介紹自己的方法。
- 創建 Student 類別,繼承自 Person 類別,並新增一個 grade 屬性。
- 為 Student 和 Teacher 類別分別定義不同的介紹方法,讓兩者的行為可以多態地運行。
- Magic Method,重定義 __str__ 方法,讓 Person 類別可以用 print() 輸出基本信息。
- 首先定義Person類別,__init__ 是一個特殊的方法,用於初始化類別的實例(對象)。當我們創建一個類別的實例時,__init__ 方法會自動執行,用於設置實例的初始屬性值或執行任何初始化的操作。
def __init__(self, name, age): self.name = name self.age = age def introduce(self): return f"Hi, I am {self.name} and I am {self.age} years old" # magic method def __str__(self) -> str: return f"Person(Name: {self.name}, Age: {self.age})" |
然後在Person類別內新增Method,class內稱Method而非Function,__str__則是Python內稱為Magic Method,假設沒有重新定義,則會顯示出class Person所存儲的位置,類似<__main__.Person object at 0x0000025AFC34E410>
"-> str"則是表示這個Method所要回傳的型態是string。
- 接下來創建 Student 類別,繼承自 Person 類別,並新增一個 grade 屬性
class Student(Person): def __init__(self, name, age, grade): super().__init__(name, age) self.grade = grade def introduce(self): return f"I am {self.name}, a student in grade {self.grade}" def __str__(self) -> str: return f"Student(Name: {self.name}, Age: {self.age}, Grade: {self.grade})" |
一樣有__init__,super().__init__(name, age)則是因為class Student(Person)的原因會繼承Person類別,self.grade = grade則表示Person類別新增grade屬性。
- 接下來創建 Teacher類別,繼承自 Person 類別,並新增一個 subject屬性,定義方式與Student類似。
class Teacher(Person): def __init__(self, name, age, subject): super().__init__(name, age) self.subject = subject def introduce(self): return f"I am {self.name}, a teacher of {self.subject}" def __str__(self) -> str: return f"Teacher(Name: {self.name}, Age: {self.age}, Subject: {self.subject})" |
- 分別為 Student 和 Teacher 類別分別定義不同的介紹方法,讓兩者的行為可以多態地運行,在introduce method輸出的字串不同。
- return f"I am {self.name}, a student in grade {self.grade}"
- return f"I am {self.name}, a teacher of {self.subject}"
- Magic Method,重定義 __str__ 方法,讓 Person 類別可以用 print() 輸出基本信息。詳細請看每個__str__定義。
- class Person: return f"Person(Name: {self.name}, Age: {self.age})"
- class Student: return f"Student(Name: {self.name}, Age: {self.age}, Grade: {self.grade})"
- class Teacher: return f"Teacher(Name: {self.name}, Age: {self.age}, Subject: {self.subject})"
接下來在main function內分別建立3種不同class內容,Person("Alice", 30),Student("Bob", 16, "10th grade"),Teacher("Charlie", 40, "Mathematics"),然後將3種不同的class放入people (type是list),接下來用for迴圈印出__str__內容,
if __name__ == "__main__": person1 = Person("Alice", 30) student = Student("Bob", 16, "10th grade") teacher = Teacher("Charlie", 40, "Mathematics") people = [person1, student, teacher] print(type(people)) for person in people: print(person) # this will call __str__ of each class which including Person, Student, Teacher # basically, the following two syntaxes are the same result print(person.introduce()) # call introduce method of each class |
以上述print(person), print(person.introduce())的寫法會輸出
<class 'list'>Person(Name: Alice, Age: 30)Hi, I am Alice and I am 30 years oldStudent(Name: Bob, Age: 16, Grade: 10th grade) I am Bob, a student in grade 10th gradeTeacher(Name: Charlie, Age: 40, Subject: Mathematics)I am Charlie, a teacher of Mathematics |
