-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest33_classmethods.py
More file actions
73 lines (53 loc) · 2.1 KB
/
test33_classmethods.py
File metadata and controls
73 lines (53 loc) · 2.1 KB
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
68
69
70
71
72
73
# Class and static methods
class Employee:
raise_amount = 1.04 # Class variable
num_of_emps = 0
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
Employee.num_of_emps += 1
def fullname(self):
return f'{self.first} {self.last}'
def apply_raise(self):
#self.pay = int(self.pay * raise_amount) # raise amount is not defined
#self.pay = int(self.pay * Employee.raise_amount) # this works
# or
self.pay = int(self.pay * self.raise_amount)
@classmethod # this is a decorator. This decorator declares the method below as a classmethod
def set_raise_amt(cls, amount): # cls is for the class. Just like self is for the instance
cls.raise_amount = amount
@classmethod # alternate constructor using a string to construct the object
def from_string(cls, emp_str):
myfirst, mylast, mypay = emp_str.split('-')
return cls(myfirst, mylast, mypay)
@staticmethod # this is how to declare a static method
def is_workday(day): # static methods do not take a class or instance
if day.weekday() == 5 or day.weekday() == 6: # 5 = Saturday, 6 = Sunday from datetime
return False
return True
emp_1 = Employee('me', 'maw', 20000)
emp_2 = Employee('test2', 'noway', 30000)
Employee.set_raise_amt(1.05)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
# Calling the class method using the class or the instance does the same thing
emp_1.set_raise_amt(1.06)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
emp_str_1 = 'John-Doe-70000'
emp_str_2 = 'Steve-Smith-30000'
emp_str_3 = 'Jane-Doe-90000'
first, last, pay = emp_str_1.split('-')
new_emp_1 = Employee(first, last, pay)
print(new_emp_1.email)
print(new_emp_1.pay)
new_emp_2 = Employee.from_string(emp_str_2)
print(new_emp_2.email)
print(new_emp_2.pay)
import datetime
my_date = datetime.date(2020, 2, 20)
print(Employee.is_workday(my_date))