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

Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

George Boorman

Curriculum Manager, DataCamp

คลาส Customer

class Customer:

# Code for class goes here
pass
  • class <name>: เริ่มต้นนิยามคลาส
  • โค้ดภายใน class ต้องเยื้องบรรทัด
  • ใช้ pass เพื่อสร้างคลาส "ว่าง"
c_one = Customer()
c_two = 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 ควรเป็นอาร์กิวเมนต์แรกของทุกเมธอด
  • self แทนออบเจกต์ที่ยังไม่ได้สร้าง
  • cust.identify("Laura") จะถูกตีความเป็น Customer.identify(cust, "Laura")
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

เราต้องการแอตทริบิวต์

  • OOP รวมข้อมูลเข้ากับเมธอดที่จัดการข้อมูลนั้น
    • ชื่อของ 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 # Will create .name when set_name is called self.name = new_name
# Create an object # .name doesn't exist here yet cust = Customer()
# .name is created and set to "Lara de Silva" cust.set_name("Lara de Silva")
print(cust.name)
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...