SoFunction
Updated on 2024-11-17

Understanding Python Methods like Methods & Static Methods

write in front of

The reading volume is honey low these days, what is the reason I didn't figure out, if you guys think I have a problem with what I wrote, or what is not good, welcome to tell me in the background or wechat, thanks in advance.

Yesterday's post. Details.Solving Class Methods - Bound and Unbound MethodsWe've written about bound and unbound methods in Methods, and today we'll move on to the remaining Class Methods and Static Methods.

Class Methods & Static Methods

Before we begin, let's look at the following piece of code:

class Sample:
 language = "C++"
 def __init__(self):
  = "python"

def get_class_attr(cls):
 return 

if __name__ == "__main__":
 print(":",)
 r = get_class_attr(Sample)
 print("get class attribute:",r)
 f = Sample()
 print("instance attribute:",)

The above code defines an attribute language = "C++" in the class Sample, which is a "class attribute", and = "python" in the initialization method, which is an "instance attribute".

Knowing this, we then analyze the function get_class_attr(cls), the parameter used in this function is cls, from the body of the function, it is required to refer to the object should have the attribute language, which means that not just any object can be. Coincidentally, the previously defined class Sample has the attribute language, so when you call this function, you directly use the class object as the argument to get_class_attr().

is to get the value of a class attribute, and get_class_attr(Sample) returns the value of the attribute of the class Sample, so for the above example, the first two print() functions should print the same result.

f = Sample() creates an instance and then accesses the instance properties. So for the above code the result is shown below:

:C++
get class attribute:C++
instance attribute:python

I don't know if you understand after my above explanation, if not, I suggest you compare the above run results and the process of analysis more carefully.

In the above example, the more special function should be get_class_attr(cls), which is written outside the class, however, this function can only call the class object written before, because not all objects have that special language attribute, this function is written outside the unfavorable to the maintenance of the later stage, we should avoid this situation, and the way to avoid it is to write the function and the class together, so there is the following way of writing. The way to avoid this is to write the function and class together, which is why we have the following style:

class sample:
 language = "C++"
 def __init__(self):
  = "python"

 @classmethod
 def get_class_attr(cls):
 return 

if __name__ == "__main__":
 print(":",)
 r = sample.get_class_attr()
 print("get class attribute:",r)
 f = sample()
 print("instance attribute:",)
 print("instance get_class_str:",f.get_class_attr())

In the modified code above, there is @classmethod, which is a decorator that we talked about in the section on functions. We should note that the first argument to the method decorated by @classmethod is not self, which is different from what we would normally recognize as a class method. The parameter cls is used here, which is the customary way of writing it, but you can use anything else. Let's take a look at the result:

:C++
get class attribute:C++
instance attribute:python
instance get_class_str:C++

As we can see from the above results, the result of get_class_attr() is the value of the class attribute regardless of whether it is executed through a class or an instance, which means that the method decorated by the decorator @classmethod, which is referenced by its parameter cls, is the class object Sample.

At this point, the definition of a "class method" comes into play: a class method is a method defined inside a class. The method is decorated by the decorator @classmethod, whose first parameter cls references the class object, i.e., the class itself is passed to the method as a reference.

Once we know about class methods, we can use the same idea to understand another method called "static methods", so let's look at a piece of code:

import random

def judge(n):
 num = (1,100)
 return num - n > 0

class Sample:
 def __init__(self,name):
  = name

 def get_name(self,age):
 if judge(age):
  return 
 else:
  return "the name is stupid"

if __name__ == "__main__":
 s = Sample('rocky')
 name = s.get_name(23)
 print(name)

First look at the code above, the class Sample inside the use of the outside function judge (n), the relationship between this class and the function is also because of the interconnection, so the maintenance of the program may be a problem later, so in order to facilitate the maintenance of the program, we have also modified the program:

import random

class Sample:
 def __init__(self,name):
  = name

 def get_name(self,age):
 if (age):
  return 
 else:
  return "the name is stupid"
 @staticmethod
 def judge(n):
 num = (1,100)
 return num - n > 0

if __name__ == "__main__":
 s = Sample('rocky')
 name = s.get_name(23)
 print(name)

Again, this is a modified optimization that puts the function that was outside the class inside the class. But it's not a simple move, you have to add the @staticmethod decorator to the front of the function, and note that even though the function is inside the class, it's not the same as any other method, and its first parameter isn't self, so when we want to use it, we can either call it from an instance, as in (n), or we can call it from a class, as in (n). when we want to use it.

As you can see from the above program, even though judge(n) is inside the class, it is really a standalone method that has nothing to do with the class itself, and is there only to eliminate the maintenance headaches described earlier. But there is a reason for it to exist, and the above example is a typical illustration.

So the definition of "static method" comes out: inside the scope of the class, it must be preceded by an @staticmethod decorator, and we name such methods static methods.

after

Methods are an important part of a class, and the class methods and static methods covered in this chapter give us a more convenient tool for working with classes.

"That's it for the "methods" piece. We'll move on to the remaining two features of OOP: polymorphism and encapsulation, so stay tuned.

If you feel that this post gives you something to gain, welcome to praise and forward, your support is the biggest power to my words, sharing is always on the road, let's cheer together.

The end。

Above is an in-depth understanding of Python methods such as methods & static methods in detail, more information about python class methods and static methods please pay attention to my other related articles!