I watched a youtube video explaining @classmethods, instance methods, and @staticmethods. I understand how to use them. I just don't understand WHEN to use them and WHY. This is the code he gave us for the @classmethods in the youtube video.
class Employee:
# class object attributes
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
Employee.num_of_emps += 1
def fullname(self):
return f'{self.first} {self.last}'
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
emp_1 = Employee('Corey', 'Shaffer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
emp_3 = Employee.from_string('Ezekiel-Wootton-60000')
print(emp_3.email)
print(emp_3.pay)
Why am I using a @classmethod for the from_string method? I think it makes more sense to use the normal instance method with no decorator because we aren't referring to the class. Right?!? We are referring to each instance in which the string is being passed as an argument.