现在的位置: 首页 > 综合 > 正文

[Python小菜]OOP概念–static method

2013年10月05日 ⁄ 综合 ⁄ 共 1263字 ⁄ 字号 评论关闭

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)

出错, 没有绑定方法

参数中加入我们上面创建的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,...)的形式

抱歉!评论已关闭.