what is the use and when to use @classmethod in python?

Question:

I have never used @classmethod and I do not think of any examples to use it, I know how it works but I do not know when it’s time to use it for example

class Example:
    def __init__(self,param1,param2):
        self.param1 = param1
        self.param2 = param2
    @classmethod
    def my_method(cls,param1,param2):
        return cls(param1,param2)

example = Example.my_method(1,2)
print(example)

output:

<__main__.Example object at 0x02EC57D0>

But why not do this?

class Example:
    def __init__(self,param1,param2):
        self.param1 = param1
        self.param2 = param2

    def my_method(self,param1,param2):
        return Example(param1,param2)

example = Example(1,2)
method = example.my_method(3,4)
print(method)

output:

<__main__.Example object at 0x02EC57D0>

It’s the same result but it does not come to mind when I could use classmethod

Asked By: Francisco

||

Answers:

There are 3 kinds of methods in python:

  • Instance method
  • Class method
  • Static Method
class Person():
    species='homo_sapiens' # This is class variable
    def __init__(self, name, age):
        self.name = name # This is instance variable
        self.age = age

    def show(self):
        print('Name: {}, age: {}.'.format(self.name, date.today().year - self.age))

    @classmethod
    def create_with_birth_year(cls, name, birth_year):
        return cls(name, date.today().year - birth_year)

    @classmethod
    def print_species(cls):
        print('species: {}'.format(cls.species))

    @staticmethod
    def get_birth_year(age):
        return date.today().year - age


class Teacher(Person):
    pass

1) Instance method (show) need an instance and must use self as the first parameter. It can access the instance through self and influence the state of an instance.

2) Class method (create_with_birth_year and print_species) need no instance and use cls to access the class and influence the state of a class. We can use @classmethod to make a factory, such as:

navy = Person.create_with_birth_year('Navy Cheng', 1989)
navy.show()

and this factory can be inherited:

zhang = Teacher.create_with_birth_year('zhang', 1980)
print(type(zhang))

and class method can be used access class variable:

Person.print_species()

3) Static Method (get_birth_year) need no special parameter(self or cls) and will change any state of a class or instance. It can privde some helper function about a class.

Answered By: Navy Cheng
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.