|
| 1 | +import datetime |
| 2 | + |
| 3 | + |
| 4 | +class Employee: |
| 5 | + # class variable is shared among all instances of a class |
| 6 | + num_of_emps = 0 |
| 7 | + raise_amount = 1.04 |
| 8 | + |
| 9 | + def __init__(self, first, last, pay): |
| 10 | + self.first = first # instance variable |
| 11 | + self.last = last |
| 12 | + self.pay = pay |
| 13 | + self.email = first + "." + last + "@company.com" |
| 14 | + Employee.num_of_emps += 1 |
| 15 | + |
| 16 | + # instance method |
| 17 | + def fullname(self): |
| 18 | + return "{} {}".format(self.first, self.last) |
| 19 | + |
| 20 | + # self is instance |
| 21 | + def apply_raise(self): |
| 22 | + # both are valid |
| 23 | + self.pay = int(self.pay * self.raise_amount) |
| 24 | + # self.pay = int(self.pay * Employee.raise_amount) |
| 25 | + |
| 26 | + def __repr__(self): |
| 27 | + return "Employee('{}', '{}', '{}')".format(self.first, self.last, self.pay) |
| 28 | + |
| 29 | + def __str__(self): |
| 30 | + return "{} - {}".format(self.fullname(), self.email) |
| 31 | + |
| 32 | + # cls is Employee |
| 33 | + @classmethod |
| 34 | + def set_raise_amount(cls, amount): |
| 35 | + cls.raise_amount = amount |
| 36 | + |
| 37 | + # alternative constructor |
| 38 | + @classmethod |
| 39 | + def from_string(cls, emp_str): |
| 40 | + first, last, pay = emp_str.split("-") |
| 41 | + # Employee("Corey", "Schafer", 50000) is the same as cls(first, last, pay)!! |
| 42 | + return cls(first, last, pay) |
| 43 | + |
| 44 | + @staticmethod |
| 45 | + def is_workday(day): |
| 46 | + if day.weekday() == 5 or day.weekday() == 6: |
| 47 | + return False |
| 48 | + return True |
| 49 | + |
| 50 | + |
| 51 | +emp_1 = Employee("Corey", "Schafer", 50000) |
| 52 | +emp_2 = Employee("Test", "Employee", 60000) |
| 53 | + |
| 54 | + |
| 55 | +Employee.set_raise_amount(1.05) |
| 56 | + |
| 57 | + |
| 58 | +Employee.raise_amount = 1.06 |
| 59 | + |
| 60 | +emp_1.set_raise_amount(1.07) |
| 61 | + |
| 62 | +print(Employee.raise_amount) |
| 63 | +print(emp_1.raise_amount) |
| 64 | +print(emp_2.raise_amount) |
| 65 | + |
| 66 | +emp_str_1 = "John-Doe-70000" |
| 67 | +emp_str_2 = "Steve-Smith-30000" |
| 68 | +emp_str_3 = "Jane-Doe-90000" |
| 69 | + |
| 70 | +first, last, pay = emp_str_1.split("-") |
| 71 | + |
| 72 | +new_emp_1 = Employee(first, last, pay) |
| 73 | + |
| 74 | +print(new_emp_1) |
| 75 | + |
| 76 | +new_emp_2 = Employee.from_string(emp_str_2) |
| 77 | + |
| 78 | +print(new_emp_2) |
| 79 | + |
| 80 | + |
| 81 | +my_date = datetime.date(2024, 7, 10) |
| 82 | + |
| 83 | +print(Employee.is_workday(my_date)) |
0 commit comments