This question already has an answer here:
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?
If you see
_randomize
method, you are not using any instance variable (declared in init) in it but it is using a classvar
i.e.RANDOM_CHOICE = 'abcdefg'
.It means, your method can exist without being an instance method and you can call it directly on class.
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.
You can read more about class and instance variable here.