what is static method?
python2.73 doc
Static method objects
Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved
from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation.
Static method objects are not themselves callable, although the objects they wrap usually are. Static method objects are created by the built-in staticmethod() constructor.
不需要自己去調用
compare
用一般類方法和靜態方法和定義和調用作為比較
定義一個普通的class A
In [40]: class A(object): ....: def met(self,a,b): ....: print a,b ....:
執行個體調用met方法
In [41]: a = A()In [42]: a.met(3,4)3 4
直接調用met方法
In [43]: A.met(3,4)---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-43-b2ef395d495e> in <module>()----> 1 A.met(3,4)TypeError: unbound method met() must be called with A instance as first argumen (got int instance instead)
出錯, 沒有Binder 方法
參數中加入我們上面建立的a執行個體
In [47]: A.met(a,3,4)3 4
只有使用類執行個體才可以調用
定義一個帶有靜態方法的類:
In [52]: class B(): ....: @staticmethod ....: def met(a,b): #靜態方法第一個參數不需要是self ....: print a,b ....:
執行個體後調用
In [55]: b = B()In [56]: b.met(3,4)3 4
直接調用
In [57]: B.met(3,4) #可以在不執行個體化的情況下直接調用函數3 4
靜態方法可以在不執行個體類的情況下直接調用,但是方法的第一個參數不能在寫成def(self,...)的形式