Bootstrap

python 中三种定义类的方式

在Python中方,有三种定义类的方法:
常规方式、@classmethod修饰方式、@staticmethod修饰方式

class类定义
In [1]: class A:
   ...:     def common(self,x):
   ...:         print "executing common(%s,%s)"% (self,x)
   ...:         print "self:",self
   ...:     @classmethod
   ...:     def class_fun(cls,x):
   ...:         print "executing class_fun(%s,%s)"%(cls,x)
   ...:         print "cls:",cls
   ...:     @staticmethod
   ...:     def static_fun(x):
   ...:         print "executig static_fun(%s)"%x

1、定义方式
这里写图片描述
注:self 和cls的区别不是强制的,指示PEP8中的一种编码风格,self通常用作实例方法的第一参数,cls通常用作类方法的第一参数。即通常用self来传递当前类对象的实例,cls传递当前类对象。
2、绑定对象
common 方法绑定对象的实例,class_fun方法绑定对象A,static_fun没有参数绑定

绑定对象
In [2]: a= A()

In [3]: a
Out[3]: <__main__.A instance at 0x10d7a4b90>

In [5]: print a.common
<bound method A.common of <__main__.A instance at 0x10d7a4b90>>

In [7]: print a.class_fun
<bound method classobj.class_fun of <class __main__.A at 0x10d84b120>>

In [8]: print a.static_fun
<function static_fun at 0x10d840e60>

3、调用方式
common可以通过实例a调用,类对象A直接调用会参数错误,但如果显示但传如实例a,则可正常显示

**common 调用**
In [9]: a.common(1)
executing common(<__main__.A instance at 0x10d7a4b90>,1)
self: <__main__.A instance at 0x10d7a4b90>

In [10]: A.common(1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-a3c19042b814> in <module>()
----> 1 A.common(1)

TypeError: unbound method common() must be called with A instance as first argument (got int instance instead)

In [11]: A.common(a,1)
executing common(<__main__.A instance at 0x10d7a4b90>,1)
self: <__main__.A instance at 0x10d7a4b90>

class_fun通过类对象或者对象实例调用

In [12]: A.class_fun(1)
executing class_fun(__main__.A,1)
cls: __main__.A

In [13]: a.class_fun(1)
executing class_fun(__main__.A,1)
cls: __main__.A

static_fun通过类对象或者实例调用


In [14]: A.static_fun(1)
executig static_fun(1)

In [15]: a.static_fun(1)
executig static_fun(1)
;