Các phương thức lớp

Nhập môn Lập trình Hướng đối tượng với Python

George Boorman

Curriculum Manager, DataCamp

Phương pháp

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
Nhập môn Lập trình Hướng đối tượng với Python

Các phương thức lớp

  • Có thể định nghĩa phương thức lớp
  • Phải có phạm vi hẹp vì họ không thể sử dụng dữ liệu ở cấp đối tượng
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...)
  • Cũng như self, cls là một quy ước nhưng bất kỳ từ nào cũng được
Nhập môn Lập trình Hướng đối tượng với Python

Các hàm tạo thay thế

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)
  • Cho phép các hàm tạo thay thế
  • Chỉ có thể có một __init__()
  • Sử dụng phương thức lớp để tạo đối tượng
  • Dùng return để trả về một đối tượng
  • cls(...) sẽ gọi __init__(...)
Nhập môn Lập trình Hướng đối tượng với Python

Các hàm tạo thay thế

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

Tệp văn bản chứa tên John Smith và mức lương 40000

# Create an employee without calling Employee()
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
Nhập môn Lập trình Hướng đối tượng với Python

Khi nào nên dùng phương thức lớp

  • Các hàm tạo thay thế

  • Các phương pháp không yêu cầu thuộc tính ở cấp thể hiện

  • Giới hạn ở một thể hiện (đối tượng) duy nhất của một lớp

    • Kết nối cơ sở dữ liệu
    • Cài đặt cấu hình
Nhập môn Lập trình Hướng đối tượng với Python

Hãy luyện tập!

Nhập môn Lập trình Hướng đối tượng với Python

Preparing Video For Download...