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?
Uses of classmethod() function are used in factory design patterns where we want to call many functions with the class name rather than an object.
You can use class methods for any methods that are not bound to a specific instance but the class. In practice, you often use class methods for methods that create an instance of the class. When a method creates an instance of the class and returns it, the method is called a factory method.
If a classmethod is intended to operate on the class and a regular instance method is intended to operate on an instance of the class, then a classmethod is best used to for functionality associated with the class, but that would not be useful if applied to an existing instance of a class.
The difference between the Class method and the static method is: A class method takes cls as the first parameter while a static method needs no specific parameters. A class method can access or modify the class state while a static method can't access or modify it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With