在学python,关于类中的方法,我知道可以定义很多种,比如参数不带self,参数带self,有@classmethod声明,参数带cls的类方法,有@staticmethod声明的静态方法。
python3.4
我之前看一本书上说,参数不带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'>
>>>