Search code examples
pythondecoratorclass-method

Why should I use a classmethod in python?


I am writing a function in some class in python, and people suggested to me to add to this function a @classmethod decorator.

My code:

import random


class Randomize:
    RANDOM_CHOICE = 'abcdefg'

    def __init__(self, chars_num):
        self.chars_num = chars_num

    def _randomize(self, random_chars=3):
        return ''.join(random.choice(self.RANDOM_CHOICE)
                       for _ in range(random_chars))

The suggested change:

    @classmethod
    def _randomize(cls, random_chars=3):
        return ''.join(random.choice(cls.RANDOM_CHOICE)
                       for _ in range(random_chars))

I'm almost always using only the _randomize function.

My question is: What is the benefits from adding to a function the classmethod decorator?


Solution

  • If you see _randomize method, you are not using any instance variable (declared in init) in it but it is using a class var i.e. RANDOM_CHOICE = 'abcdefg'.

    import random
    
    class Randomize:
        RANDOM_CHOICE = 'abcdefg'
    
        def __init__(self, chars_num):
            self.chars_num = chars_num
    
        def _randomize(self, random_chars=3):
            return ''.join(random.choice(self.RANDOM_CHOICE)
                           for _ in range(random_chars))
    

    It means, your method can exist without being an instance method and you can call it directly on class.

      Randomize._randomize()
    

    Now, the question comes does it have any advantages?

    • I guess yes, you don't have to go through creating an instance to use this method which will have an overhead.

      ran = Randomize() // Extra steps
      ran._randomize()   
      

    You can read more about class and instance variable here.