Python類別 – 本篇會介紹Python Class, Python Method, Python Inheritance, Python Interface (類型仿作, Python 無 Interface 這keyword) 的基礎用法. Let’s Start!
句型 | 例子: |
interface (父類別名稱){ //父類別內容 } | class Person: def __init__(self, name, surname): self.name = name self.surname = surname def GetFullName(self): return self.name + ” ” + self.surname |
句型 | 例子: |
class (類別名稱) : (抽象類別名稱){ //類別內容 //可引用父類別內容 //在例子中: string GetFullName } | class Student(Person): def __init__(self, name, surname): super().__init__(name, surname); self.chiGrade = 0 self.engGrade = 0 self.mathsGrade = 0 def isChiPassed(): if self.chiGrade < 50: return false; return true; |
class (類別名稱) : (抽象類別名稱){ //類別內容 //可引用父類別內容 //在例子中: string GetFullName } | class Teacher(Person): def __init__(self, name, surname, schoolName, teachingGrade): super().__init__(name, surname); self.schoolName = schoolName self.teachingGrade = teachingGrade def isTeachingPassed(self): if chiGrade < 50: return false; return true; |
句型 | 例子: |
class (介面名稱){ //介面內容 } | class ICheckedPassed: def isPassed(): return false; |
句型 | 例子: |
class (類別名稱) : (介面名稱){ //類別內容 //必須展開介面內容 //在例子中: bool isPassed() } | class Student(Person, ICheckedPassed): def __init__(self, name, surname): super().__init__(name, surname); self.chiGrade = 0 self.engGrade = 0 self.mathsGrade = 0 def isChiPassed(self): if self.chiGrade < 50: return false; return true; def isPassed(): return isChiPassed() && isEngPassed() && isMathsPassed(); |
句型 | 例子: |
class (類別名稱) : (介面名稱){ //類別內容 //必須展開介面內容 //在例子中: bool isPassed() } | class Teacher(Person, ICheckedPassed): def __init__(self, name, surname, schoolName, teachingGrade): super().__init__(name, surname); self.schoolName = schoolName self.teachingGrade = teachingGrade def isTeachingPassed(self): if chiGrade < 50: return false; return true; def isPassed(): return isTeachingPassed(); |
相關頁面:
Python 介面 (類作模仿) – Interface的基本用法 – 加入 for loop, if, Array, Collection的例子