1

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.

  • The idea is that `set_raise_amt` changes the amount for *all* employees, not this specific one. And `from_string` takes all the information it needs on the command line, so it doesn't need an instance. – Charles Duffy Aug 06 '18 at 14:57
  • thanks dude for this example. – zero May 21 '19 at 18:30

1 Answers1

2

In the case of from_string, it's so it can be used as an alternative constructor. It's usage is like so

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.


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:

Employee.raise_amt = x
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47