Python 絕招分類:三種常見 method 差在哪?
先前我們介紹了 static method,是一種跟物件無關、不需要用到 self 的絕招,只要是 class 就可以直接使用。
但其實除了 static method,Python 中還有另外兩種常見的 method 類型唷~
- Instance Method(實例方法)
- Class Method(類別方法)
- Static Method(靜態方法)
那我們來看看這三種方法有什麼差別吧~
1. Instance Method:這是物件的專屬絕招!
這是很常見的 method,第一個參數會是 self,代表這個方法是某個物件在使用的。不同的物件(機器)使用時,可以有不同的表現。
class Robot:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f”Hello! I am {self.name}”)
這裡 say_hello() 就是 instance method,因為它需要 self,呼叫時會依照不同的機器名稱說出不同的話。
r1 = Robot(” Jerry “)
r2 = Robot(” Karel “)
r1.say_hello()
r2.say_hello()
顯示結果就會像這樣
Hello! I am Jerry
Hello! I am Karel
2. Class Method:這是工廠級的絕招!
如果我們今天只需要使用「工廠的資訊」而不是「機器的資訊」的時候,那就可以使用 class method!
它的第一個參數會是 cls,代表整個 class(工廠)本身。
class Robot:
version = “1.0”
@classmethod
def show_version(cls):
print(f”Robot version: {cls.version}”)
這裡 show_version() 是 class method,可以用 Robot.show_version() 呼叫,或是用物件呼叫也行,但都會顯示 class 的資料(像是版本號)。
3. Static Method:不管哪台機器都一樣
static method 是為了因應不需要用到 self 的時候而誕生的!因為今天不會使用到任何物件裡的資料。
很像是大家都可以一起使用這個絕招功能,有點類似是一個 公告欄。
class Robot:
@staticmethod
def say_hi():
print(“Hi, welcome to stanCode !”)
這個 say_hi() 方法可以不用創造物件就執行,直接使用 Robot.say_hi() 呼叫。
那如果我們已經做了r1 Jerry 機器人了,也可以直接用 r1.say_hi() 呼叫這個絕招來使用!但因為這個方法與物件無關,所以其實本質仍是呼叫 class 自己的功能~
所以無論是專屬每台機器的 instance method
或是代表整間工廠的 class method
還是所有人都能使用的 static method
這三種方法絕招都有自己適合的場景!
如果可以理解它們的差別,那我們在設計 class 的時候,一定可以寫出更清晰、專業又容易維護的程式碼!
stanCode標準程式教育機構-你也值得更好的教育
Facebook|https://www.facebook.com/stancode.tw
Instagram|https://www.instagram.com/stancode_tw/
YouTube|https://www.youtube.com/@stancode7228/videos
Website|https://www.stancode.tw/
TikTok|https://www.tiktok.com/@standardcoding
