類別是 Python 物件導向程式設計的核心。本文系統梳理類別定義語法、__init__/__del__ 生命週期方法、單繼承與方法覆寫、實例屬性與類別屬性區別,並提供可直接執行的完整範例碼。
類別是物件的藍圖,定義屬性(資料)與方法(行為):
class 類別名稱(父類別名稱): # 父類別可選
成員變數 = 初始值
def 方法名稱(self, 參數):
方法主體
self 慣例代表實例本身(類似 C++ this),必須作為實例方法第一參數。
>>> class pp: pass
>>> p = pp()
>>> print(p)
<__main__.pp instance at 0x00CA77B0>
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print('Hello, my name is', self.name)
>>> p = Person('Swaroop')
>>> p.sayHi()
Hello, my name is Swaroop
重點:__init__ 在物件建立時自動調用,用於設定實例屬性。
class Person:
population = 0
def __init__(self, name):
self.name = name
print('(Initializing %s)' % self.name)
Person.population += 1
def __del__(self):
print('%s says bye.' % self.name)
Person.population -= 1
def howMany(self):
print('We have %d persons here.' % Person.population)
>>> A = Person('aa')
(Initializing aa)
>>> B = Person('bb')
(Initializing bb)
>>> # 程式結束或 del 觸發 __del__
aa says bye.
bb says bye.
注意:__del__ 在記憶體回收時調用,非確定性;不可依賴它釋放關鍵資源(請用 with/try-finally)。
class CAnimal:
name = 'unname' # 類別屬性
def __init__(self, voice='hello'):
self.voice = voice # 實例屬性
def __del__(self):
pass
def Say(self):
print(self.voice)
class CDog(CAnimal): # 繼承
def SetVoice(self, voice):
self.voice = voice
def Run(self, voice): # 覆寫
print('Running')
bobo = CDog()
bobo.SetVoice('My Name is BoBo!')
bobo.Say() # My Name is BoBo!
bobo.Run() # Running
| 概念 | 說明 | 範例 |
|---|---|---|
| 類別屬性 | 所有實例共享,定義於類別體 | population = 0 |
| 實例屬性 | 每個實例獨有,在 __init__ 設定 | self.name = name |
| 繼承 | 子類別擁有父類別所有屬性/方法 | class CDog(CAnimal) |
| 方法覆寫 | 子類別重新定義同名方法 | def Run(self, voice) |
| super() | 調用父類別方法(Python 3 簡化語法) | super().__init__(name) |
__init__ 完整初始化所有實例屬性def __init__(self, name: str) -> None:)提升可讀性__del__ 執行複雜邏輯或 I/O 操作