เมธอดของคลาส

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

George Boorman

Curriculum Manager, DataCamp

เมธอด

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

    def give_raise(self, amount):
        self.salary += amount


# Unique attribute values emp_one = Employee("John", 40000)
emp_one.give_raise(5000) print(emp_one.salary)
45000









# Unique attribute values emp_two = Employee("Jane", 60000)
emp_two.give_raise(5000) print(emp_two.salary)
65000
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

เมธอดของคลาส

  • สามารถกำหนดเมธอดของคลาสได้
  • ต้องมีขอบเขตที่แคบ เพราะไม่สามารถใช้ข้อมูลระดับอ็อบเจกต์ได้
class MyClass:
    # Use a decorator to declare a class method
    @classmethod

# cls argument refers to the class def my_awesome_method(cls, args...): # Do stuff here # Can't use any instance attributes
# Call the class, not the object MyClass.my_awesome_method(args...)
  • เช่นเดียวกับ self คำว่า cls เป็นเพียงชื่อที่นิยมใช้ แต่จะใช้คำใดก็ได้
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Constructor ทางเลือก

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

@classmethod def from_file(cls, filename): with open(filename, "r") as f: # Read the first line name = f.readline().strip() # Read the second line as integer salary = int(f.readline().strip())
return cls(name, salary)
  • ช่วยให้มี constructor ทางเลือกได้
  • กำหนด __init__() ได้เพียงตัวเดียว

 

  • ใช้เมธอดของคลาสเพื่อสร้างอ็อบเจกต์
  • ใช้ return เพื่อคืนค่าอ็อบเจกต์
  • cls(...) จะเรียกใช้ __init__(...)
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Constructor ทางเลือก

class Employee:
  def __init__(self, name, salary):
      self.name = name
      self.salary = salary
  @classmethod
  def from_file(cls, filename):
      with open(filename, "r") as f:
          name = f.readline().strip()
          salary = int(f.readline().strip())
      return cls(name, salary)  

Employee.txt

ไฟล์ข้อความที่มีชื่อ John Smith และเงินเดือน 40000

# Create an employee without calling Employee()
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

เมื่อใดควรใช้เมธอดของคลาส

  • Constructor ทางเลือก

  • เมธอดที่ไม่จำเป็นต้องใช้แอตทริบิวต์ระดับอินสแตนซ์

  • การจำกัดให้มีอินสแตนซ์ (อ็อบเจกต์) เดียวของคลาส

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

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

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

Preparing Video For Download...