Python inspect将方法识别为FunctionType而不是types.MethodType

时间:2014-08-20 08:25:53

标签: python python-3.x introspection

我正在尝试使用python检查模块检查源代码。我在这种情况下检查的代码示例是:

class xxx:

    def __init__(self):
        pass

    def xxxmethod(self):
        pass

我希望当我检查这段代码并检查'xxxmethod'的类型时,它将是types.MethodType。 同样建议here,我用它来接收函数元素:

found_function = getattr(class_element, method_name, None)

但是它的类型是types.FunctionType而不是types.MethodType。

当我使用getmembers()打印class_element的内容时,

('xxxmethod', <function xxxmethod at 0x00000000028EC6C8>)

这是字典中的元素。

为什么它的行为如此?我忽视了什么吗?

编辑:从范围字典中接收class_element。它是否与这个类的实例没有关系?

谢谢!

1 个答案:

答案 0 :(得分:2)

Python 2和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不再具有未绑定方法的概念而进一步混淆。