Python使用@staticmethod和@classmethod分別建立方法

建立一個student類,使用@staticmethod和@classmethod分別建立static_f和class_f兩個方法,調用體會差異

class student: 

 @staticmethod 

 def static_f(): 

 print 'staticmethod,沒有參數,調用方法:student.static_f()' 


 @staticmethod 

 def static_f(name): 

 print 'staticmethod,參數名:' + name +'調用方法:student.static_f('name')' 


 @staticmethod

 def static_f(cls): 

 print 'staticmethod,參數名:' + cls +'調用方法:student.static_f('cls'),這裏的cls只是一個普通的參數,不能用student.static_f()調用' 


@classmethod 

 def class_f(cls): 

 print 'classmethod,調用方法:student.class_f()' 


 @classmethod

 def class_f(cls, name): 

 print 'classmethod,參數名:' + name +'調用方法:student.class_f('name')'


# @classmethod創建方法時,必須有至少一個參數,cls或者self不可省略

# @staticmethod創建方法時,可以不含參數,當含參數時,cls或者self都是普通參數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章