最後活躍 10 months ago

此 Python 類別可根據台灣勞動法的新制或舊制規則,計算勞工應得的資遣費,適用於 HR、企業管理者或員工自我估算補償金額。

修訂 52bb5714ae0d4ccdde154f8d558897bc984370de

severance_pay_calculator.py 原始檔案
1class SeverancePayCalculator:
2 """
3 Legendary 級資遣費計算器,適用於新制與舊制。
4 - 自動計算應得資遣費
5 - 內建異常處理與日誌紀錄
6 """
7
8 def __init__(self, salary, years_of_service, policy="new", log=True):
9 """
10 初始化資遣費計算器
11 :param salary: 每月工資 (int or float)
12 :param years_of_service: 服務年數 (float)
13 :param policy: "new" (新制) 或 "old" (舊制)
14 :param log: 是否啟用日誌 (bool)
15 """
16 self.salary = salary
17 self.years_of_service = years_of_service
18 self.policy = policy.lower()
19 self.log_enabled = log
20 self.log(f"初始化: 工資={salary}, 年資={years_of_service}, 政策={policy}")
21
22 def log(self, message):
23 """ 簡單的日誌紀錄 """
24 if self.log_enabled:
25 from datetime import datetime
26 timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
27 print(f"[{timestamp}] {self.__class__.__name__}: {message}")
28
29 def calculate(self):
30 """ 計算資遣費 """
31 try:
32 if self.policy == "new":
33 severance_pay = min(self.years_of_service * 0.5, 6) * self.salary
34 elif self.policy == "old":
35 severance_pay = min(self.years_of_service, 6) * self.salary
36 else:
37 raise ValueError("政策類型錯誤,請選擇 'new''old'")
38
39 result = round(severance_pay, 2)
40 self.log(f"計算結果: {result}")
41 return result
42 except Exception as e:
43 self.log(f"錯誤: {e}")
44 return None
45
46 def __str__(self):
47 return f"{self.policy.upper()} 制資遣費: {self.calculate()}"
48
49# 測試範例
50if __name__ == "__main__":
51 salary = 100000 # 每月工資
52 years_of_service = 8.5 # 服務年數
53
54 new_policy_calculator = SeverancePayCalculator(salary, years_of_service, "new")
55 old_policy_calculator = SeverancePayCalculator(salary, years_of_service, "old")
56
57 print(new_policy_calculator)
58 print(old_policy_calculator)
59