[PYTHON] Various class methods and static methods

Introduction

In this article, I'll write about what a "class method" is. Articles up to the last time ↓ ↓ ↓ About python properties

What is a class method?

In a nutshell, it's a "method that can be used directly from a class, like a class variable." (A method is a function in a class)

@classmethod
def method name(cls,Argument 1,Argument 2, ...): 

This is the form of the class method. There are some differences from the functions we've seen so far, so it's easy to tell. (1) Since the instance (entity) does not exist,'self' that represents itself is not prepared. (2) An argument called'cls' is prepared instead of'self', and the object of the class in which the class method is stored is assigned.

When calling a class method, it is possible to call it directly from the class.

#Calling a class method
name of the class.Class method name()

#For normal methods
hello =name of the class#Instance creation
hello.Method name#Method call

Be careful when using it, as the calling part is also different.

Class variables

I mentioned a class method earlier as "a method that can be used directly from a class like a class variable". But if you don't know what a class variable is in the first place, I think it's a refreshing thing. The class variable is the "message" part of the code below.

class Lesson:
    message = 'OK'

    def print(self):
        print(Lesson.message)

le = Lesson()            #Instance creation
le.print()               #print method call
Lesson.message = 'Welcome!'    #'message'The contents of the variable'Welcome!'change to
le.print()                     #again'print method'call
print(Lesson.message)          #Also call the class variable messsage

I don't think it's that difficult because it's no different from a normal variable.

As you can see at the very end, you can call it directly from the class without creating an instance. This is because, unlike methods (those with def), the values are stored in the class itself, not in the instance.

A class method is a combination of class variables and methods. It can be called directly from the class and can be easily changed.

Example of using class method

class MyObj:
  message = 'OK'
  
  @classmethod
  def print(cls):
    print(cls.message)
    
MyObj.print()   #OK
MyObj.message = 'Welcome!'
MyObj.print()   #Welcome!
print(MyObj.message)  #Welcome!

#For normal methods
#mo = MyObj()
#mo.print()

You can see that you can call it directly from the class without creating an instance. You can see that it is different from the normal method because you can easily change the value.

Create an instance

Now, let's prepare a normal method and a class method and check how they behave when an instance is created.

class A():
  count = 0
  def __init__(self):
    A.count += 1      #Every time an instance is created'count'Is added
  def exclaim(self):
    print('I am an A!')
  @classmethod
  def kids(cls):
    print('A has', cls.count, 'title objects.')   #Show how many times it was counted
    
a = A()   #Create an instance
b = A()   #Create an instance
c = A()   #Create an instance
A.kids()  #Calling a class method'A has 3 title objects.'

This is one'count'added each time an instance is created.

After creating an instance three times with'a',' b', and'c', the class method is called to display how many times it has been counted. Since the instance has been created 3 times, you can see that'count'is added by '3'. When you call the class method, it is not added because the instance is not created.

What is the difference between a class method and a method or function?

I would like to summarize the differences between them here.

#Class method
@classmethod
def method name(cls,Argument 1,Argument 2, ...): 
#Method
def method name(self,Argument 1,Argument 2, ...): 
#function
def function name():

You can see the difference by arranging them like this. ① Difference between class method and method -> Methods can only be called by creating an instance, but class methods can be called directly from the class.

② Difference between class method and function -> You can get the class itself called'cls' as the first argument. Another difference is that it is in a class, so you can use it by importing the class.

Static method

From here, we will explain about static methods. A static method is a class method, but the difference is that you don't have to specify any arguments. Let's actually see it.

@staticmethod
def method name():
     print("This is a static method.")

#call
name of the class.Method name()

At the time of class method, there was something called'cls' in the first argument, but static method does not. It is easy to understand if you think that it is almost the same as the method. It is not often used, but it is characterized by being able to be called directly from the class like the class method.

At the end

In this article, I wrote about "class methods" and "static methods". Articles will be updated in the future. Articles up to the last time ↓ ↓ ↓ About python properties

Recommended Posts

Various class methods and static methods
Class methods and static methods
Example of using class variables and class methods
[Python] Difference between class method and static method
Class method static method
About Class and Instance
[python] class basic methods
Python: Class and instance variables
Various import methods of Mnist
Python class variables and instance variables
Class inheritance and super functions
Various of Tweepy. Ma ♡ and ♡ me ♡
I'll inherit and override the class
Combinatorial optimization-typical problems and execution methods
Use instance method and class method properly
perl objects and python class part 2.
Python class definitions and instance handling
Calculation of homebrew class and existing class
(For myself) Flask_ex (templates and static)
perl objects and python class part 1.
Python classes and instances, instance methods