Why should I use a classmethod in python? [duplicate]

爷,独闯天下 提交于 2019-12-01 01:09:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/43437117/why-should-i-use-a-classmethod-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!