2

I was trying to think of use cases of the @classmethod special decorator besides creating an "overloaded" (I guess not really overloaded since the method name would be different from init) constructor, but couldn't think of any.

I've checked out posts like What's an example use case for a Python classmethod? but could only find use cases that point to the alternate constructor.

One other case I could think of was to couple a method with a class to encapsulate related logic (as mentioned by @samplebias in the post linked above), but I think @staticmethod is more suitable for enclosing related logic to a class (as someone commented on the post by @samplebias).

Could anyone help me identify some additional use cases for this special decorator?

elllot
  • 365
  • 4
  • 13
  • I've only ever used it for alternate constructors. I've **never** used @staticmethod – juanpa.arrivillaga Dec 19 '17 at 19:37
  • If I have a base class and 4 subclasses inherit from base, I would like to modify the flow logic or change parts of it based on which subclass the method is called from. Then I need the (sub)class that this method is called from. Then I need classmethod. – percusse Dec 19 '17 at 19:42
  • Another use case might be to set default values for new instances (for example, for network-related stuff, you might want to set a default timeout, default host, etc). You could do that by setting attributes of the class, but if it's common to want to set several at once, a class method might be handy. – kindall Dec 19 '17 at 19:52
  • Hmm... So basically a case where we want to define a method that modifies class attributes? I think that makes sense as static methods are not really meant to alter the class? – elllot Dec 19 '17 at 20:32
  • Static methods *can't* alter the class, since they don't get a reference to it. (Well, they could via the class's name, but that would break inheritance.) – kindall Dec 19 '17 at 21:54
  • Ah I see... So maybe I just need to identify a context where the class object is being modified? – elllot Dec 30 '17 at 18:32

1 Answers1

0

I was going through some material on OOP with Python and found a use case of the @classmethod decorator besides as an overloaded constructor.

It makes sense to use class methods when acting (altering) directly on the class object. For example, if you have an Employee object and base_raise_factor as a class variable, it would make sense to create a class method on Employee to alter this variable.

You could argue we could just set Employee.base_raise_factor to something directly, but I think it's better to adhere to encapsulation and not modify the internals directly. Plus, we could define some additional logic in the class method that updates base_raise_factor.

elllot
  • 365
  • 4
  • 13