关于python类中的方法

在学python,关于类中的方法,我知道可以定义很多种,比如参数不带self,参数带self,有@classmethod声明,参数带cls的类方法,有@staticmethod声明的静态方法。

我之前看一本书上说,参数不带self的方法(上面说的第一种),就是类方法,但是我不清楚它和上面第三种第四种的区别,于是就做了这么一个实验。发现对于这件事情,python2和python3的处理方式是不一样的,看结果:


python2.7

>>> class A:
...  def fun():
...    print 'no self'
...  def fun2(self):
...    print 'self'
...  @classmethod
...  def fun3(cls):
...    print 'cls'
...  @staticmethod
...  def fun4():
...    print 'static'
...
>>> A.fun()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unbound method fun() must be called with A instance as first argument (got nothing instead)
>>> A.fun3()
cls
>>> A.fun4()
static
>>> A.fun2()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unbound method fun2() must be called with A instance as first argument (got nothing instead)
>>> a = A()
>>> a.fun2()
self
>>> a.fun()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: fun() takes no arguments (1 given)
>>> type(A.fun)
<type 'instancemethod'>
>>>
>>> type(A.fun2)
<type 'instancemethod'>
>>>
>>> type(A.fun3)
<type 'instancemethod'>
>>>
>>> type(A.fun4)
<type 'function'>
>>>

python3.4

>>> class A:
...   def fun1():
...     print('no self')
...   def fun2(self):
...     print('self')
...   @classmethod
...   def fun3(cls):
...     print('cls')
...   @staticmethod
...   def fun4():
...     print('static')
...
>>> A.fun1()
no self
>>> A.fun2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fun2() missing 1 required positional argument: 'self'
>>> A.fun3()
cls
>>> A.fun4()
static
>>> a = A()
>>> a.fun1()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fun1() takes 0 positional arguments but 1 was given
>>> a.fun2()
self
>>> a.fun3()
cls
>>> a.fun4()
static

>>> type(A.fun1)
<class 'function'>
>>>
>>> type(A.fun2)
<class 'function'>
>>>
>>> type(A.fun3)
<class 'method'>
>>>
>>> type(A.fun4)
<class 'function'>
>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值