Python - OOP 物件導向


Posted by pei_______ on 2022-05-24

OOP主要架構與使用

class Employee:

    ## Attribute 屬性

    # Class Attribute: 所有Object共用
    raise_amount = 1.05

    # Instanve Attribute: 隸屬個別Objevt
    def __init__(self, first, last, pay: float):
        self.first = first
        self.last = last
        self.pay = pay



    ## Method 方法

    # Static Method: 不受Class內任何變數影響
    @staticmethod
    def is_workday(day):
        if day.weekday() == 5 or day.weekday() == 6:
            return False
        return True

    # Class Method: 針對Class變數執行
    @classmethod
    def set_raise_amount(cls, amount):
        cls.raise_amount = amount

    # Instance Method: 針對Object變數執行
    def apply_raise(self):
        self.pay = int(self.pay * Employee.raise_amount)

創建Object

emp_1 = Employee("penny", "lee", 30000)
emp_2 = Employee("Leo", "Wu", 50000)

使用Method

# Static Method

from datetime import datetime
print(Employee.is_workday(datetime.today()))


# 從Class/Object級別訪問 Class Attribute
# 若該Object(emp)無此變數,則會自動到父級別(Employee)取得

print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
> 1.05 1.05 1.05


# 以Object改變Class Attribute不會影響原數值(1.05)

emp_1.raise_amount = 1.08
> 1.05 1.08 1.05


# 以Class Method改變Class Attribute則皆會影響原數值(1.05)

Employee.set_raise_amount(1.01)
emp_1.set_raise_amount(1.1) # 會改變class variable
> 1.1 1.1 1.1

OOC 繼承

class Developer(Employee):
    raise_amount = 1.1

    # 繼承父類別屬性,並另外建立新的屬性
    def __init__(self, first, last, pay: float, prog_lang):
        super().__init__(first, last, pay)
        self.prog_lan = prog_lang
class Manager(Employee):

    # 屬性內部嵌入預設值
    def __init__(self, first, last, pay: float, employees=None):
        super().__init__(first, last, pay)
        if employees is None:
            self.employees = []
        else:
            self.employees = employees

    def add_employee(self, employee):
        if employee not in self.employees:
            self.employees.append(employee)

    def rm_employee(self, employee):
        if employee in self.employees:
            self.employees.remove(employee)

    def print_emp(self):
        for emp in self.employees:
            print(f"--->  {emp.full_name}")

查詢: 類別/物件下所屬的屬性等資料
print(Employee.__dict__)

查詢: 物件是否為類別的實體化
print(isinstance(man_4, Employee))

查詢: 類別是否為另一類別鼅子類別
print(issubclass(Manager, Employee))


Property設置與使用

class Employee:

    # Getter: 將Method改變成以Attribute方式讀取
    @property
    def email(self):
        return f"{self.first}.{self.last}@gmail.com"

    @property
    def full_name(self):
        return f"{self.first} {self.last}"

    # Setter: 該Method(Property)的設置
    @full_name.setter
    def full_name(self, name):
        first, last = name.split(' ')
        self.first = first
        self.last = last

    # Deleter: 該Method(Property)的刪除
    @full_name.deleter
    def full_name(self):
        print("Delete Name!")
        self.first = None
        self.last = None

Property呼叫方法

# Getter
emp_1 = Employee("penny", "lee", 30000)
print(emp_1.email)
> penny.lee@gmail.com

# Setter
emp_1.full_name = 'Tommy Yu'
print(emp_1.email)
> Tommy.Yu@gmail.com

# Deleter
del emp_1.full_name
print(emp_1.first)
> None

設置Class的Magic Method

什麼是Magic Method
1 + 3 = add(1, 3)a + b = add('a', 'b') 會自動轉化為
int.__add__(1, 3) 以int的add function執行
str.__add__('a', 'b') 以str的add function執行

設置Employee型態的Magic Method

def __add__(self, other):
    return self.pay + other.pay

print(emp_1 + emp_2)

#Python #常用匯整







Related Posts

初見狀態管理工具 Vuex (4) - Modules

初見狀態管理工具 Vuex (4) - Modules

JS30 Day 29 筆記

JS30 Day 29 筆記

Day4 真不想承認啊,因為自己太過年輕所犯下的錯誤

Day4 真不想承認啊,因為自己太過年輕所犯下的錯誤


Comments