Why should I use a classmethod in python?

This question already has an answer here:

  • Meaning of @classmethod and @staticmethod for beginner? 12 answers
  • What are Class methods in Python for? 15 answers

  • If you see _randomize method, you are not using any instance variable (declared in init) in it but it is using a class var ie 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.

    链接地址: http://www.djcxy.com/p/54270.html

    上一篇: 为什么这个类的实例被覆盖?

    下一篇: 为什么我应该在python中使用classmethod?