what is the use and when to use @classmethod in python? [duplicate]
Asked Answered
H

1

17

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

Hiltner answered 19/1, 2019 at 4:31 Comment(3)
Now imagine you inherit from this class. You will always get an Example instance instead of one from your subclass.Laciniate
Your example is a classic use of classmethods (constructors). The reason to use those instead of regular methods is that you don't have to initialize an instance to use them. Imagine your class' __init__ did something like open a network connection or consume some sort of resource; you wouldn't want to create an instance just to create other instances. You could just call Example.my_method() without having any actual Example instances. Also this question might be helpful #38738Matheson
@KlausD. can you please elaborate with an example?Claiborne
B
29

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.

Bracy answered 19/1, 2019 at 5:58 Comment(1)
This was a super clear and simple way to understand the different methods - better than tutorials found online - thanks!Ethnology

© 2022 - 2024 — McMap. All rights reserved.