Original address: http://blog.csdn.net/caroline_wendy/article/details/23383995
static functions (Staticmethod), class functions (Classmethod), differences in member functions (fully parsed)
Defined:
static function (@staticmethod): A static method that deals primarily with the logical association of this class, such as validating data;
class function (@classmethod): A class method that focuses more on invoking a method from a class than invoking a method in an instance, such as constructing an overload;
member function: The method of the instance, can only be called through the instance;
Code:
#-*-coding:utf-8-*- #Eclipse Pydev, Python 3.3#by C.l.wang classA (object): _g= 1deffoo (self,x):Print('executing foo (%s,%s)'%(self,x)) @classmethoddefClass_foo (cls,x):Print('executing Class_foo (%s,%s)'%(cls,x)) @staticmethoddefStatic_foo (x):Print('executing static_foo (%s)'%x) a=A () A.foo (1) A.class_foo (1) A.class_foo (1) A.static_foo (1) A.static_foo ('Hi') Print(A.foo)Print(A.class_foo)Print(A.static_foo)
Output:
Executing foo (<__main__. A Object at 0x01e2e1b0>,1) executing Class_foo (<class '__main__. A'>,1) executing Class_foo (<class '__main__. A'>,1) executing Static_foo (1) executing static_foo (HI)<bound Method A.foo of <__main__. A object at 0x01e2e1b0>> <bound method Type.class_foo of <class '__main__. A'>> <function A.static_foo at 0x01e7e618>
Specific application:
For example, the date method can be instantiated (__init__) for data output;
Data conversion can be done through the class method (@classmethod) ;
Data validation can be performed by static methods (@staticmethod) ;
Code:
- #-*-Coding:utf-8-*-
- #eclipse Pydev, Python 3.3
- #by C.l.wang
- 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
- def display (self):
- return "{0}*{1}*{2}". Format (self.day, self.month, self.year)
- @classmethod
- def from_string (cls, date_as_string):
- Day, month, year = map (int, date_as_string.split ('-'))
- Date1 = CLS (Day, month, year)
- return date1
- @staticmethod
- def is_date_valid (date_as_string):
- Day, month, year = map (int, date_as_string.split ('-'))
- return Day <= and month <= <= 3999
- Date1 = Date (' one ', ' one ', ' all ')
- Date2 = date.from_string (' 11-13-2014 ')
- Print (Date1.display ())
- Print (Date2.display ())
- Print (Date2.is_date_valid (' 11-13-2014 '))
- Print (Date.is_date_valid (' 11-13-2014 '))
Output:
12*11*2014 11*13*2014 false false
Reference:
Http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner
Http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python
Python-static function (Staticmethod), class function (Classmethod), member function difference (full parse)