Python 物件導向入門(三):解開 self 的秘密,讓物件會做更多事!
在上一篇,我們讓「寵物領養中心」裡的每一隻寵物,都可以用 say_hello() 和我們打招呼,還學會用 __str__() 讓印出物件時能夠獲得我們想要的資訊!
我們在製作這些 Method 的時候,你可能會發現一件事,為什麼每個 Method 裡面都有 self?它到底是誰?
所以今天我們就要來解開 self 的秘密,讓我們的寵物領養中心繼續進化,新增更多好用的功能!
self 是什麼?
先記得一個重點,self 就代表「自己的那隻物件」。
可以把它想像成「呼叫的是哪一隻,此時 self 就是屬於那一隻」。
當我們呼叫 lucky.say_hello() 時,self 現在就是屬於 lucky 的,
而如果是 karel.say_hello(),那 self 現在就是屬於 karel 的!
所以我們 say_hello() 的絕招中
print(f”Hi, my name is {self.name}, I’m a {self.species}!”)
就等於在說:「把自己的名字及什麼動物來印出來」。
沒有 self,方法就不知道要用誰的資料!
今天如果我們沒有 self,那在使用 Method 的時候,它就根本不知道要使用哪一隻寵物(物件)的名字、年齡或品種
所以你也可以把 self 想像成,工廠內部溝通的管道,也可以看成是 Method 裡「連回去自己的物件的那條線」
沒有這條線或管道,Method 就像迷路的機器手臂,找不到它應該拿什麼資料來操作。
把我們的領養中心加上更多 Method 吧!
class Pet:
def __init__(self, name, age, species):
self.name = name
self.age = age
self.species = species
def say_hello(self):
print(f”Hi, my name is {self.name}, I’m a {self.species}!”)
def birthday(self):
self.age += 1
print(f”Happy birthday, {self.name}! You are {self.age} years old!”)
def introduce(self):
print(f”My name is {self.name}, I’m a {self.age}-year-old {self.species}.”)
def __str__(self):
return f”{self.name} is a {self.age}-year-old {self.species}”
一樣來看看每個 Method 顯示的結果吧!
lucky = Pet(“Lucky”, 3, “Dog”)
lucky.say_hello()
➜ Hi, my name is Lucky, I’m a Dog!
lucky.birthday()
➜ Happy birthday, Lucky! You are now 4 years old!
lucky.introduce()
➜ My name is Lucky, I’m a 4-year-old Dog.
Tips:如果沒有 self,Method 就像無頭蒼蠅;有了 self,Method 就能操作屬於自己的資料,self 這就是物件導向的重點核心之一!
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
