A method is a function of the static class, no instances. Static method is mainly used to store the code logic, and logically belong to the class, but the class itself, and no relationship, i.e. in a static method, properties and methods do not involve the operation of the class. Can be understood as a static method is an independent, simple function, it is only namespace hosted a class, easy to use and maintain.
For example, I want to define a class about the time of the operation, which has a function of the current time of acquisition. Using a static method, however, did not use the method body (not used), or the class instance attributes (or methods). To get the current time when the character string does not necessarily need to instantiate an object, this time for the static method, more of a class where the name space. In fact, we can write a similar function to do these things outside of class, but to do so would upset the logical relationship can lead to future code maintenance difficult.
import time class TimeTest(object): def __init__(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second # Various methods are omitted @staticmethod # static method DEF the showTime (): return The time.strftime ( " % H:% M:% S " , time.localtime ()) print (TimeTest.showTime ()) t = TimeTest(2, 10, 10) print(t.showTime()) ''' Perform output: 21:05:43 21:05:43 '''
See the code below, the process-oriented half and half is object-oriented. For complete object-oriented programming, the process-oriented code is not allowed. Fully object-oriented programming. Examples of login first. There is not a specific target when necessary to perform the login method, this is unreasonable. You need to login () becomes a static method.
DEF the Login (): Pass # username # password # identity - instantiated class Student: def __init__(self,name):pass def login(self):pass
We built a python is a function staticmethod static method to the class as defined function, it does not need to instantiate. So, even the self argument at all.
class Student: def __init__(self,name):pass @staticmethod DEF Login () : # . Login class is a static method of static methods no default parameters, it can be used as a normal function User = INPUT ( ' User: ' ) IF User == ' Tony ' : Print ( ' Success ' ) the else : Print ( ' faild ' ) Student.login()
to sum up:
-
When a method is to use the properties of an object by conventional means;
-
When a method to use a static property class is a class method (a classmethod);
-
When a method of the object's properties to be neither static nor class attributes, methods can be used staticmethod static;