ในบทช่วยสอนนี้ เราจะเรียนรู้เกี่ยวกับ self ใน Python คุณคุ้นเคยแล้วหากทำงานกับ Python เราจะดูรายละเอียดที่น่าสนใจ
หมายเหตุ − self ไม่ใช่ keyword ใน Python
เริ่มจากการใช้งาน self ที่พบบ่อยที่สุดใน Python
เราใช้ self ในคลาสเพื่อแทน instance ของ object เราสามารถสร้าง instance หลายตัวของคลาส และแต่ละ instance จะมีค่าต่างกัน self ช่วยให้เราเข้าถึงค่า property ภายใน instance นั้นๆ ได้ ลองดูตัวอย่าง
ตัวอย่าง
# คลาส
class Laptop:
# init method
def __init__(self, company, model):
# self
self.company = company
self.model = model
เรากำหนด property ของคลาสเป็น self.[something] ดังนั้นทุกครั้งที่สร้าง instance ของ class self จะอ้างอิงถึง instance ที่ต่างกันซึ่งเรากำลังเข้าถึง property หรือ method
มาสร้าง instance 2 ตัวของคลาส Laptop และดูว่า self ทำงานอย่างไร
ตัวอย่าง
# คลาส
class Laptop:
# init method
def __init__(self, company, model):
# self
self.company = company
self.model = model
# สร้าง instance สำหรับคลาส Laptop
laptop_one = Laptop('Lenovo', 'ideapad320')
laptop_two = Laptop('Dell', 'inspiron 7000')
# พิมพ์ property ของ instances
print(f"Laptop One: {laptop_one.company}")
print(f"Laptop Two: {laptop_two.company}")
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้
Laptop One: Lenovo Laptop Two: Dell
เราได้ชื่อต่างกันสำหรับ property เดียวกัน มาดูรายละเอียดเบื้องหลัง
Python ส่ง reference ไปยัง instance โดยอัตโนมัติขณะเข้าถึง methods หรือ properties และ reference นี้ถูกจับใน self ดังนั้นแต่ละ instance reference จะต่างกัน และเราจะได้ property ของ instance นั้นๆ
เรารู้ว่า self ไม่ใช่ keyword ของ Python มันเป็นเหมือนอาร์กิวเมนต์ที่คุณไม่ต้องส่งขณะเข้าถึง property หรือ method ของ instance
Python จะส่ง reference ของ instance ให้อัตโนมัติ เราสามารถจับ reference นี้ด้วยชื่อตัวแปรอะไรก็ได้ ลองรันโค้ดดู
ตัวอย่าง
import inspect
# คลาส
class Laptop:
# init method
def __init__(other_than_self, company, model, colors):
# self ไม่ใช่จริงๆ
other_than_self.company = company
other_than_self.model = model
other_than_self.colors_available = colors
# method
def is_laptop_available(not_self_but_still_self, color):
# return ว่ามีโน้ตบุ๊กสีที่ระบุหรือไม่
return color in not_self_but_still_self.colors_available
# สร้าง instance
laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black'])
# เรียก is_laptop_available โดยไม่มี keyword color
print("Available") if laptop.is_laptop_available('Silver') else print("Not available")
print("Available") if laptop.is_laptop_available('White') else print("Not available")
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้
Available Not available
เราเปลี่ยนชื่อ self เป็น อะไรก็ได้ แต่มันยังทำงานเหมือนเดิม ไม่มีความแตกต่าง ดังนั้น self ไม่ใช่ keyword และเราสามารถเปลี่ยนเป็นชื่ออื่นได้ มันเป็นเหมือนอาร์กิวเมนต์
หมายเหตุ − แนวทางปฏิบัติที่ดีคือใช้ self เป็นมาตรฐานที่ทุก Python programmer ปฏิบัติ
สรุป
self คือ reference ของ instance ไม่ใช่ keyword สามารถเปลี่ยนชื่อได้ แต่มาตรฐานคือ self หากมีข้อสงสัย กรุณาแจ้งในส่วนความคิดเห็น