In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Many beginners are not very clear about the difference between @ classmethod and @ staticmethod. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.
In Python object-oriented programming, the methods defined in classes can be either @ classmethod decorated class methods or @ staticmethod decorated static methods, and the most commonly used are instance methods without decorators. If we put these methods together, it is undoubtedly confusing for beginners, so how should we use them correctly?
Let's start with a simple example:
Class A (object):
Def M1 (self, n):
Print ("self:", self)
@ classmethod
Def m2 (cls, n):
Print ("cls:", cls)
@ staticmethod
Def m3 (n):
Pass
A = A ()
A.m1 (1) # self:
A.m2 (1) # cls:
A.m3 (1)
I have defined a total of three methods in the class. M1 is the instance method, and the first parameter must be self. M2 is a class method, the first parameter must be cls (also established by convention), m3 is a static method, and the parameters are optional according to business requirements. Some of these things happen when the program is running (combined with the figure below).
Step 1: the code executes the class command from the first line, which creates a class An object (yes, the class is also an object, everything is an object) and initializes the properties and methods in the class, remember that the instance object has not been created yet.
The second and third steps: then execute astata (), and the system automatically calls the constructor of the class to construct the instance object a
Step 4: then call a.m1 (1). M1 is the instance method, and the instance object is automatically passed to the self parameter for binding, that is, both self and a point to the same instance object.
Step 5: when calling A.m2 (1), python implicitly passes the class object to the cls parameter, and both cls and A point to the class object.
Strictly speaking, the one on the left is the name of the variable, the reference to the object, and the right is the real object. For convenience of description, I directly call a the object. You should understand that the object is actually the real object on the right that it refers to.
Let's take a look at the characteristics of each method.
Instance method print (A.m1)
# A.m1 is displayed in py2 as
Print (a.m1)
A.m1 is a method that has not yet bound an instance object. For an unbound method, an instance object must be passed in explicitly when calling A.m1, while a.m1 is a method that has already bound an instance. Python implicitly passes the object to the self parameter, so it no longer passes parameters manually, which is the process of calling the instance method.
A.m1 (a, 1)
# equivalent
A.m1 (1)
If the unbound method A.m1 does not pass an instance object to self, a missing parameter error will be reported. In py3 and py2, the error reported is not the same. Python2 requires that the first parameter, self, is an instance object, while any object can be found in python3.
A.m1 (1)
TypeError: M1 () missing 1 required positional argument:'n' class method print (A.m2)
Print (a.m2)
M2 is a class method, whether it is A.m2 or a.m2, it is a method that has been automatically bound to class object A, for the latter, because python can find the class to which it belongs through instance object a, and automatically bind to cls after finding A.
A.m2 (1)
# equivalent
A.m2 (1)
This allows us to call class and static methods in an instance method by using self.m2 ().
Def M1 (self, n):
Print ("self:", self)
Self.m2 (n) static method print (A.m3)
Print (a.m3)
M3 is a static method in a class, no different from an ordinary function, and has no so-called binding relationship with classes and instances, it just happens to exist a function in the class. This method can be referenced either through a class or an instance.
A.m3 (1)
# equivalent
A.m3 (1)
The above is the basic introduction of several methods. Now that we've sorted out a few basic concepts, let's talk about the usage scenarios between several methods and their advantages and disadvantages.
Application scenario
Scenarios where static methods are used:
If you do not need to access any instance methods and properties in a method, simply by passing in parameters and returning data, then it is suitable to be defined by static methods, which saves the overhead cost of instantiating objects. Often, it is no problem that the module layer outside the class exists as a function, but in the class, it only serves this class.
For example, the following is an example of verifying a Wechat signature in the development of a Wechat official account, which does not refer to any class or instance-related properties or methods.
From hashlib import sha1
Import tornado.web
Class SignatureHandler (tornado.web.RequestHandler):
Def get (self):
"
Judge whether the request comes from Wechat according to the signature
"
If self._check_sign (TOKEN, timestamp, nonce, signature):
Self.write (echostr)
Else:
Self.write ("you are not a request from Wechat")
@ staticmethod
Def _ check_sign (token, timestamp, nonce, signature):
Sign = [token, timestamp, nonce]
Sign.sort ()
Sign = "" .join (sign)
Sign = sha1 (sign). Hexdigest ()
Return sign = = signature
The usage scenarios of class methods are:
Creating instance objects as factory methods, such as the built-in module datetime.date class, makes extensive use of class methods as factory methods to create date objects.
Class date:
Def _ _ new__ (cls, year, month=None, day=None):
Self = object.__new__ (cls)
Self._year = year
Self._month = month
Self._day = day
Return self
@ classmethod
Def fromtimestamp (cls, t):
Y, m, d, * = _ time.localtime (t)
Return cls (y, m, d)
@ classmethod
Def today (cls):
T = _ time.time ()
Return cls.fromtimestamp (t)
If you want to call a static class on the method side, it is appropriate to define the method as a class method, because if it is defined as a static method, you have to explicitly reference class A, which is not a good thing for inheritance.
Class A: @ staticmethod def M1 () pass @ staticmethod def m2 (): A.m1 () # bad @ classmethod def m3 (cls): cls.m1 () # good is helpful to you after reading the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.