severance_pay_calculator.py
· 1.3 KiB · Python
Исходник
class SeverancePayCalculator:
def __init__(self, salary, years_of_service, policy="new"):
"""
初始化資遣費計算器
:param salary: 每月工資 (int or float)
:param years_of_service: 服務年數 (float)
:param policy: "new" (新制) 或 "old" (舊制)
"""
self.salary = salary
self.years_of_service = years_of_service
self.policy = policy.lower()
def calculate(self):
""" 計算資遣費 """
if self.policy == "new":
severance_pay = min(self.years_of_service * 0.5, 6) * self.salary
elif self.policy == "old":
severance_pay = min(self.years_of_service, 6) * self.salary
else:
raise ValueError("政策類型錯誤,請選擇 'new' 或 'old'")
return round(severance_pay, 2)
def __str__(self):
return f"{self.policy.upper()} 制資遣費: {self.calculate()} 元"
# 測試範例
if __name__ == "__main__":
salary = 100000 # 每月工資
years_of_service = 8.5 # 服務年數
new_policy_calculator = SeverancePayCalculator(salary, years_of_service, "new")
# old_policy_calculator = SeverancePayCalculator(salary, years_of_service, "old")
print(new_policy_calculator)
# print(old_policy_calculator)
| 1 | class SeverancePayCalculator: |
| 2 | def __init__(self, salary, years_of_service, policy="new"): |
| 3 | """ |
| 4 | 初始化資遣費計算器 |
| 5 | :param salary: 每月工資 (int or float) |
| 6 | :param years_of_service: 服務年數 (float) |
| 7 | :param policy: "new" (新制) 或 "old" (舊制) |
| 8 | """ |
| 9 | self.salary = salary |
| 10 | self.years_of_service = years_of_service |
| 11 | self.policy = policy.lower() |
| 12 | |
| 13 | def calculate(self): |
| 14 | """ 計算資遣費 """ |
| 15 | if self.policy == "new": |
| 16 | severance_pay = min(self.years_of_service * 0.5, 6) * self.salary |
| 17 | elif self.policy == "old": |
| 18 | severance_pay = min(self.years_of_service, 6) * self.salary |
| 19 | else: |
| 20 | raise ValueError("政策類型錯誤,請選擇 'new' 或 'old'") |
| 21 | |
| 22 | return round(severance_pay, 2) |
| 23 | |
| 24 | def __str__(self): |
| 25 | return f"{self.policy.upper()} 制資遣費: {self.calculate()} 元" |
| 26 | |
| 27 | # 測試範例 |
| 28 | if __name__ == "__main__": |
| 29 | salary = 100000 # 每月工資 |
| 30 | years_of_service = 8.5 # 服務年數 |
| 31 | |
| 32 | new_policy_calculator = SeverancePayCalculator(salary, years_of_service, "new") |
| 33 | # old_policy_calculator = SeverancePayCalculator(salary, years_of_service, "old") |
| 34 | |
| 35 | print(new_policy_calculator) |
| 36 | # print(old_policy_calculator) |
| 37 | |
| 38 |