Why am I using a @classmethod instead of a normal instance method [duplicate]

Clash Royale CLAN TAG#URR8PPP
Why am I using a @classmethod instead of a normal instance method [duplicate]
This question already has an answer here:
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.
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
set_raise_amt
from_string
1 Answer
1
In the case of from_string, it's so it can be used as an alternative constructor. It's usage is like so
from_string
new_employee = Employee.from_string('Corey-Shaffner-50000')
Think about it, if I wanted to construct my first Employee using this method, how would I do that if it was an instance method? I don't have any instances yet to call it on.
Employee
In the case of set_raise_amt, this is so it is clear you are editing a class (aka static) variable, not an instance variable. That being said, it is generally considered poor python to use getters and setters. The user should just be able to do:
set_raise_amt
Employee.raise_amt = x
The idea is that
set_raise_amtchanges the amount for all employees, not this specific one. Andfrom_stringtakes all the information it needs on the command line, so it doesn't need an instance.– Charles Duffy
Aug 6 at 14:57