Python - 静态函数(staticmethod), 类函数(classmethod), 成员函数


定义: 静态函数(@staticmethod): 即静态方法,主要处理与这个类的逻辑关联, 如验证数据;

         类函数(@classmethod):即类方法, 更关注于从类中调用方法, 而不是在实例中调用方法, 如构造重载;

         成员函数: 实例的方法, 只能通过实例进行调用;

 1 # -*- coding: utf-8 -*-  
 2   
 3 #eclipse pydev, python 3.3  
 4 #by C.L.Wang  
 5   
 6 class A(object):  
 7       
 8     _g = 1  
 9       
10     def foo(self,x):  
11         print('executing foo(%s,%s)'%(self,x))  
12  
13     @classmethod  
14     def class_foo(cls,x):  
15         print('executing class_foo(%s,%s)'%(cls,x))  
16  
17     @staticmethod  
18     def static_foo(x):  
19         print('executing static_foo(%s)'%x)     
20   
21 a = A()  
22 a.foo(1)  
23 a.class_foo(1)  
24 A.class_foo(1)  
25 a.static_foo(1)  
26 A.static_foo('hi')  
27 print(a.foo)  
28 print(a.class_foo)  
29 print(a.static_foo)  

具体应用: 比如日期的方法, 可以通过实例化(__init__)进行数据输出; 可以通过类方法(@classmethod)进行数据转换; 可以通过静态方法(@staticmethod)进行数据验证;

 1 # -*- coding: utf-8 -*-  
 2   
 3 #eclipse pydev, python 3.3  
 4 #by C.L.Wang  
 5   
 6 class Date(object):  
 7   
 8     day = 0  
 9     month = 0  
10     year = 0  
11   
12     def __init__(self, day=0, month=0, year=0):  
13         self.day = day  
14         self.month = month  
15         self.year = year  
16           
17     def display(self):  
18         return "{0}*{1}*{2}".format(self.day, self.month, self.year)  
19      
20     @classmethod  
21     def from_string(cls, date_as_string):  
22         day, month, year = map(int, date_as_string.split('-'))  
23         date1 = cls(day, month, year)  
24         return date1  
25      
26     @staticmethod  
27     def is_date_valid(date_as_string):  
28         day, month, year = map(int, date_as_string.split('-'))  
29         return day <= 31 and month <= 12 and year <= 3999  
30       
31 date1 = Date('12', '11', '2014')  
32 date2 = Date.from_string('11-13-2014')  
33 print(date1.display())  
34 print(date2.display())  
35 print(date2.is_date_valid('11-13-2014'))  
36 print(Date.is_date_valid('11-13-2014'))