Python inspect将方法识别为FunctionType而非types.MethodType
我正在尝试使用Python的inspect模块来查看源代码。这里有一个我正在检查的代码示例:
class xxx:
def __init__(self):
pass
def xxxmethod(self):
pass
我本来期待在检查这段代码时,查看'xxxmethod'的类型会是types.MethodType。正如这里所提到的,我使用这个方法来获取函数元素:
found_function = getattr(class_element, method_name, None)
但它的类型却是types.FunctionType,而不是types.MethodType。
当我使用getmembers()打印class_element的内容时,
('xxxmethod', <function xxxmethod at 0x00000000028EC6C8>)
在字典中显示的就是这个元素。
为什么会这样呢?我是不是漏掉了什么?
补充说明:class_element是从作用域字典中获取的。这是否与这不是类的实例有关?
谢谢!
1 个回答
2
Python 2和Python 3在这方面是有区别的。
在Python 2中,你会得到一个:
<type 'instancemethod'>
但是如果你打印这个方法,会得到:
<unbound method A.m>
而在Python 3中,你会得到:
<class 'function'>
这主要是因为你是在类上查找这个方法。
在Python 2中,通过类访问这个方法会返回一个叫做“未绑定方法”的东西。Python 3中不再有“未绑定方法”这个概念了。
如果你实际创建了这个类的一个实例,在Python 2中你会再次得到:
<type 'instancemethod'>
如果你打印出来,会显示:
<bound method A.m of <__main__.A instance at 0x10ae7ad40>>
而在Python 3中:
<class 'method'>
这相当于Python 2中的实例方法,打印出来的结果是:
<bound method A.m of <__main__.A object at 0x10063c6d8>>
所以,是的,问题在于你没有在类的实例上查找这个方法。而且Python 3不再有“未绑定方法”这个概念,这让事情变得更加复杂。