แอตทริบิวต์ระดับคลาส vs. ระดับอินสแตนซ์

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

George Boorman

Curriculum Manager, DataCamp

หลักการสำคัญของ OOP

Encapsulation:

  • การรวมข้อมูลและเมธอดเข้าด้วยกัน

Inheritance:

  • การขยายฟังก์ชันการทำงานของโค้ดที่มีอยู่

Polymorphism:

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

แอตทริบิวต์ระดับอินสแตนซ์

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

emp1 = Employee("Teo Mille", 50000) 
emp2 = Employee("Marta Popov", 65000)
  • ค่าของ name และ salary เป็นของแต่ละออบเจกต์
  • self ใช้กำหนดค่าให้กับออบเจกต์
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

แอตทริบิวต์ระดับคลาส

  • ข้อมูลที่แชร์ร่วมกันระหว่างทุกอินสแตนซ์ของคลาส

 

  • กำหนด class attributes ในส่วนตัวของ class

 

  • ทำหน้าที่เป็น "ตัวแปรส่วนกลาง" ภายในคลาส
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การสร้าง class-level attributes

class Employee:
    # Define a class attribute
    # No self. syntax
    MIN_SALARY = 30000 

def __init__(self, name, salary): self.name = name # Use class name # to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salary
else: self.salary = Employee.MIN_SALARY
  • MIN_SALARY ใช้ร่วมกันระหว่างทุกอินสแตนซ์
  • อย่าใช้ self เพื่อ กำหนด class attribute
  • ตามธรรมเนียมให้ใช้ตัวพิมพ์ใหญ่
  • ใช้ ClassName.ATTR_NAME เพื่อ เข้าถึง ค่า class attribute
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

แอตทริบิวต์ระดับคลาส

class Employee:
    # Define a class attribute
    MIN_SALARY = 30000    

def __init__(self, name, salary): self.name = name # Use class name # to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salary else: self.salary = Employee.MIN_SALARY
emp1 = Employee("John", 40000)
print(emp1.MIN_SALARY)
30000
emp2 = Employee("Jane", 60000)
print(emp2.MIN_SALARY)
30000
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การแก้ไข class-level attributes

emp1 = Employee("John", 40000)
emp2 = Employee("Jane", 60000)

# Update MIN_SALARY of emp1 emp1.MIN_SALARY = 50000
# Print MIN_SALARY for both employees print(emp1.MIN_SALARY) print(emp2.MIN_SALARY)
50000
30000
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การแก้ไข class-level attributes

  • MIN_SALARY ถูกสร้างขึ้นในนิยามของคลาส

 

  • การอัปเดต MIN_SALARY ของออบเจกต์จะไม่กระทบค่าในนิยามคลาส

 

  • ความปลอดภัย — ป้องกันการเปลี่ยนแปลงในซอฟต์แวร์!
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

ทำไมต้องใช้ class attributes?

ค่าคงที่ส่วนกลางที่เกี่ยวข้องกับคลาส

 

  • ค่าต่ำสุดและสูงสุดของแอตทริบิวต์
    • ป้องกันข้อมูลที่ไม่ถูกต้อง
  • ค่าและค่าคงที่ที่ใช้บ่อย เช่น host, port สำหรับคลาส Database
    • หลีกเลี่ยงการกำหนดค่าซ้ำเมื่อสร้างออบเจกต์
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

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

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

Preparing Video For Download...