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)
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值