+ 2

What's the benefit of using classmethods?

i been watching videos of this topic because i found this kinda complicated,this is an example of a classmethod class Employee: raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay def apply_raise(self): self.pay = self.pay * self.raise_amt @classmethod def set_raise_amt(cls, amount): cls.raise_amt = amount emp1 = Employee("user", "test", 1200) emp2 = Employee("use2", "test2", 12000) Employee.set_raise_amt(1.05) print(Employee.raise_amt) print(emp1.raise_amt) print(emp2.raise_amt) Employee.raise_amt = 1.02 print(Employee.raise_amt) print(emp1.raise_amt) print(emp2.raise_amt) but as you can see, i got the same result changing the class attribute instead of using this class method ... so i dont understand the real use of classmethods

1st Jan 2019, 7:43 PM
Razf
Razf - avatar
2 Réponses
+ 1
Okay, I'm not confident with classes yet myself, but since this thread is still silent, let me give it a try. The encapsulation idea is that you store away the mechanics and data of a type and only define a few access points (like buttons on a radio) to control change and behaviour. To set an instance's data, you define a setter method that controls how the data is entered; to get the data, a getter is the controlling entity. A class method is used without handing over the instance and accesses the class directly. So in the context of your class, the classmethod would be the setter for the class attribute. It defines that the class attribute should be changed over the class itself, not over any instance. So you'd 'privatize' that class attribute using _. In Python this is only a virtual encapsulation, 'consenting adults' and all, but I guess, this is the idea.
1st Jan 2019, 10:11 PM
HonFu
HonFu - avatar
0
Encapsulation, via the class method, helps with readability of the code. It's also a simpler way, in my estimation, to define a function of a class without resorting to changing the class's primary argument or making another class for instantiating different results based in changing the non-method function(s) of the class. In the example given, apply_raise(self) is the non-method function, and without the @classmethod set_raise_amt, changing how apply_raise works could be far more work and become more complex. So, and this is my hypothesis, set_raise_amt allows a function/class call to be accessible after changing the class with its non-method function(s). IOW, changing how a raise is determined and applied is easier to do and easier to get the result via the @classmethod.
2nd Jan 2019, 3:33 PM
Preston
Preston - avatar