以下是通过 inspect 库获取类内方法的两端代码:
Python2
>>> class A(object):
... def a(self):
... print('a')
...
... @staticmethod
... def b():
... print('b')
...
... @classmethod
... def c(cls):
... print('c')
...
>>> import inspect
>>> inspect.getmembers(A, inspect.ismethod)
[('a', <unbound method A.a>), ('c', <bound method type.c of <class '__main__.A'>>)]
Python3
>>> class A(object):
... def a(self):
... print('a')
...
... @staticmethod
... def b():
... print('b')
...
... @classmethod
... def c(cls):
... print('c')
...
>>> import inspect
>>> inspect.getmembers(A, inspect.ismethod)
[('c', <bound method A.c of <class '__main__.A'>>)]
可以看到对于类而言,实例方法在 Python3 中已经不再是method,而是function。
>>> inspect.getmembers(A, inspect.isfunction)
[('a', <function A.a at 0x10d46e598>), ('b', <function A.b at 0x10d46e620>)]
通过查阅两个版本的 inspect 文档可以看到在Python2中:
inspect.ismethod(object)
Return true if the object is a bound or unbound method written in Python.
相对于在Python3中:
inspect.ismethod(object)
Return true if the object is a bound method written in Python.
ismethod不在包含 unbound method 了。
这是否是 Python2 到 Python3 后的通识区别?可惜这么重要的区别并没有被大多数的 “ Differences between Python2 and Python3 ” 之类的文章提到。