โครงสร้างของคลาส: แอตทริบิวต์และเมธอด

การเขียนโปรแกรมเชิงวัตถุใน Python

Alex Yarosh

Content Quality Analyst @ DataCamp

คลาสเบื้องต้น

class Customer:

# code for class goes here
pass
  • class <name>: เริ่มต้นนิยามคลาส
  • โค้ดภายใน class ต้องเยื้องเข้า
  • ใช้ pass เพื่อสร้างคลาส "ว่างเปล่า"
c1 = Customer()
c2 = Customer()
  • ใช้ ClassName() เพื่อสร้างออบเจกต์จากคลาส ClassName
การเขียนโปรแกรมเชิงวัตถุใน Python

เพิ่มเมธอดให้คลาส

class Customer:  

    def identify(self, name):   
      print("I am Customer " + name)
  • การนิยามเมธอด = การนิยามฟังก์ชันภายในคลาส
  • ใช้ self เป็นอาร์กิวเมนต์แรกในการนิยามเมธอด
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • ละ self เมื่อเรียกเมธอดจากออบเจกต์
การเขียนโปรแกรมเชิงวัตถุใน Python
class Customer:  

    def identify(self, name):   
      print("I am Customer " + name)

cust = Customer()
cust.identify("Laura")

self คืออะไร?

  • คลาสเป็นแม่แบบ แล้วจะอ้างถึงข้อมูลของออบเจกต์แต่ละตัวได้อย่างไร?
  • self เป็นตัวแทนของออบเจกต์ที่ใช้ในนิยามคลาส
  • ควรเป็นอาร์กิวเมนต์แรกของทุกเมธอด
  • Python จัดการ self ให้อัตโนมัติเมื่อเรียกเมธอดจากออบเจกต์:

cust.identify("Laura") จะถูกตีความเป็น Customer.identify(cust, "Laura")

การเขียนโปรแกรมเชิงวัตถุใน Python

ทำไมต้องมีแอตทริบิวต์

  • Encapsulation: การรวมข้อมูลเข้ากับเมธอดที่ทำงานกับข้อมูลนั้น
  • เช่น ชื่อของ Customer ควรเป็นแอตทริบิวต์

  $$\text{\Large{Attributes are created by assignment (=) in methods}}$$

การเขียนโปรแกรมเชิงวัตถุใน Python

เพิ่มแอตทริบิวต์ให้คลาส

class Customer:  
    # set the name attribute of an object to new_name
    def set_name(self, new_name):

# Create an attribute by assigning a value self.name = new_name # <-- will create .name when set_name is called
cust = Customer()                   # <--.name doesn't exist here yet

cust.set_name("Lara de Silva") # <--.name is created and set to "Lara de Silva"
print(cust.name) # <--.name can be used
Lara de Silva
การเขียนโปรแกรมเชิงวัตถุใน Python

เวอร์ชันเดิม

class Customer:  



    # Using a parameter
    def identify(self, name):   
      print("I am Customer" + name)
cust = Customer()

cust.identify("Eris Odoro")
I am Customer Eris Odoro

เวอร์ชันใหม่

class Customer:  
   def set_name(self, new_name): 
      self.name = new_name

    # Using .name from the object it*self*
    def identify(self):     
      print("I am Customer" + self.name)
cust = Customer()
cust.set_name("Rashid Volkov")
cust.identify()
I am Customer Rashid Volkov
การเขียนโปรแกรมเชิงวัตถุใน Python

มาฝึกกันเถอะ!

การเขียนโปรแกรมเชิงวัตถุใน Python

Preparing Video For Download...