Python

Difference between @staticmethod and @classmethod in Python

January 11, 2022

Difference between @staticmethod and @classmethod in Python

In this article we’ll learn what the difference between @staticmethod and @classmethod, and in which situations we should use each of them.

Difference between @staticmethod and @classmethod cover

Hey you all programmers, okay? Let’s learn more about Python!

First, it’s good to understand the methods, which are basically the actions that an object has

A function, defined by def, within a class

From there we have the bifurcation between @classmethod and @staticmethod, which are also methods but with different properties

@classmethod is basically a method that implicitly passes the class as the first argument, when you define a method as classmethod, you probably want to use it by the class and not by the instance of the class

But it can be called by both the class and the instance.

In @staticmethod, on the other hand, we have a function that implicitly passes neither the object nor the class as a parameter, it’s basically a function inside the class.

It’s usually used when you have a function that executes logic that interacts with the object/class, then you can create a staticmethod for this purpose

Let’s see an example running the three cases:

class Test(object):
 
 def normalMethod(self):
  print("Olá sou um método normal")

 @classmethod
 def classMethod(cls, self):
  print("Sou um método de:")
  print(cls)
  print("Chamado por: ")
  print(self)

 @staticmethod
 def staticMethod():
  print("E sou um método estático")
  obj = Teste()
  obj.normalMethod()

Test.classmethod(Teste)
obj.classMethod(obj)

# calling static method
obj.staticMethod()

In this case we illustrate all the possibilities of a method, classmethod and staticmethod

Notice the outputs, the classmethod method was also called by the Class

Conclusion

In this article we learned the difference between @staticmethod and @classmethod

Basically, staticmethod is a function of a class that interacts in some way with the object, it could be loose in the code, but for organization and maintenance we put it in the class

@classmethod, on the other hand, is a special way of declaring a method that can be called either by the object’s class or instance, and a big detail is that we need to explicitly pass the class as an argument

Want to learn more about Python? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x