實例與類別資料

Python 物件導向程式設計

Alex Yarosh

Content Quality Analyst @ DataCamp

OOP 核心原則

 

繼承

  • 擴充既有程式的功能

多型

  • 建立一致的介面

封裝

  • 將資料與方法打包
Python 物件導向程式設計

實例層級資料

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

emp1 = Employee("Teo Mille", 50000) 
emp2 = Employee("Marta Popov", 65000)
  • namesalary實例屬性
  • self 綁定到某個實例
Python 物件導向程式設計

類別層級資料

  • 由類別的所有實例共享的資料
  • class 本體中定義類別屬性
class MyClass:
    # Define a class attribute
    CLASS_ATTR_NAME = attr_value


  • 類別內的「全域變數」
Python 物件導向程式設計

類別層級資料

class Employee:
  # Define a class attribute
  MIN_SALARY = 30000    #<--- no self. 

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 來_定義_類別屬性
  • ClassName.ATTR_NAME 來_存取_類別屬性的值
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("TBD", 40000)
print(emp1.MIN_SALARY)
30000
emp2 = Employee("TBD", 60000)
print(emp2.MIN_SALARY)
30000
Python 物件導向程式設計

為何使用類別屬性?

與類別相關的全域常數

 

  • 屬性的最小值/最大值
  • 常用值與常數,例如 Circle 類別的 pi
  • ...
Python 物件導向程式設計

類別方法

  • 方法本就「共享」:每個實例跑同一份程式碼
  • 類別方法不能用實例層級資料
class MyClass:

  @classmethod                         # <---use decorator to declare a class method

def my_awesome_method(cls, args...): # <---cls argument refers to the class # Do stuff here # Can't use any instance attributes :(
MyClass.my_awesome_method(args...)
Python 物件導向程式設計

替代建構子

class Employee:
  MIN_SALARY = 30000
  def __init__(self, name, salary=30000):
      self.name = name
      if salary >= Employee.MIN_SALARY:
        self.salary = salary
      else:
        self.salary = Employee.MIN_SALARY
  • 只能有一個 __init__()

  @classmethod
  def from_file(cls, filename):
      with open(filename, "r") as f:
          name = f.readline()
      return cls(name)

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

替代建構子

class Employee:
  MIN_SALARY = 30000
  def __init__(self, name, salary=30000):
      self.name = name
      if salary >= Employee.MIN_SALARY:
        self.salary = salary
      else:
        self.salary = Employee.MIN_SALARY

  @classmethod
  def from_file(cls, filename):
      with open(filename, "r") as f:
          name = f.readline()
      return cls(name)        

包含員工姓名單行的文字檔

# 不用直接呼叫 Employee() 也能建立員工
emp = Employee.from_file("employee_data.txt")
type(emp)
__main__.Employee
Python 物件導向程式設計

一起來練習吧!

Python 物件導向程式設計

Preparing Video For Download...