1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| from datetime import date from abc import ABC, abstractmethod
class Employee(ABC): __count = 0 def __init__(self, name, hire_year): self.name = name self._hire_year = hire_year Employee.__count += 1 @property def years_of_service(self): return date.today().year - self._hire_year @abstractmethod def calculate_salary(self): pass @classmethod def get_employee_count(cls): return cls.__count def __str__(self): return f"{self.name}({self.years_of_service}年工龄)"
class FullTimeEmployee(Employee): def __init__(self, name, hire_year, base_salary, bonus_rate): super().__init__(name, hire_year) self.__base = base_salary self.__bonus_rate = bonus_rate @property def base_salary(self): return self.__base @base_salary.setter def base_salary(self, value): if value > 0: self.__base = value def calculate_salary(self): return self.__base * (1 + self.__bonus_rate)
class ContractEmployee(Employee): def __init__(self, name, hire_year, hourly_rate, hours): super().__init__(name, hire_year) self.hourly_rate = hourly_rate self.hours = hours def calculate_salary(self): return self.hourly_rate * self.hours
emp1 = FullTimeEmployee("张三", 2018, 10000, 0.2) emp2 = ContractEmployee("李四", 2020, 100, 160)
print(Employee.get_employee_count())
employees = [emp1, emp2] for e in employees: print(f"{e}: {e.calculate_salary():.2f}元")
|