“unbound method”的含义在 Python2 和 Python3 中是否已经改变

https://www.v2ex.com/t/452551

以下是通过 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 ” 之类的文章提到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值