類別方法

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:
    # 用裝飾器宣告類別方法
    @classmethod

# 參數 cls 指向類別本身 def my_awesome_method(cls, args...): # 在這裡處理 # 不能使用實例屬性
# 呼叫類別,不是物件 MyClass.my_awesome_method(args...)
  • self 一樣,cls 是慣例,任意名稱都可
Python 物件導向程式設計入門

替代建構子

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)
  • 提供替代建構子
  • __init__() 只能有一個

 

  • 用類別方法建立物件
  • return 傳回物件
  • cls(...) 會呼叫 __init__(...)
Python 物件導向程式設計入門

替代建構子

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 的文字檔

# 不用直接呼叫 Employee() 建立員工
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
Python 物件導向程式設計入門

何時使用類別方法

  • 替代建構子

  • 不需實例層級屬性的方式

  • 將類別限制為單一實例(物件)

    • 資料庫連線
    • 設定參數
Python 物件導向程式設計入門

一起來練習吧!

Python 物件導向程式設計入門

Preparing Video For Download...