Both of these methods in Python are done through decorators.
Static Methods:
You do not need to pass an instance of a class object or class
You can pass an instance of the class. Method name A (). foo () or class name. Method A.foo () name to access
When the subclass inherits the parent class, and when the subclass is instantiated, the instance is actually the parent class, not the child class.
The invocation of a static method is the same as a call to a normal method , except that the preceding class name is added.
Static methods are not too large to use, mainly considering the encapsulation of code, maintainability
Class method:
The default transitive class object itself is CLS, which can of course take advantage of the methods in the class
You can pass an instance of the class. Method name A (). foo () or class name. Method A.foo () name to access
Methods work correctly when subclasses inherit from parent class
Class Date (object):
Day = 0
Month = 0
Year = 0
def __init__ (self, day=0, month=0, year=0): #存储初始的信息
Self.day = Day
Self.month = Month
Self.year = Year
Print Self.day, Self.month, self.year
@classmethod
def from_string (cls,date_string):
Day, month, year = map (int, date_string.split ('-'))
Date1 = CLS (Day, month, year) #cls是个类对象, not an instance
Return Date1 #返回Date实例
def foo (self):
print ' I am foo ' #普通的方法
@staticmethod
def is_date_valid (date_string): #验证方法封装在类中
Day, month, year = map (int, date_string.split ('-'))
Return day <= and month <= <= 3999
---------------------------------------------------------------------------------------------
A=date (a)
1 2 3
>>> a=date.from_string (' 09-08-2015 ')
9 8 2015
>>> A.foo ()
I am Foo
>>> date.is_date_valid (' 10-10-2015 ')
True
>>> type (date.is_date_valid)
<type ' function ' >
Python Staticmethod&classmethod