检查函数是否在 Python 类中定义

问题描述

在 Python 3.7+ 中检查函数是否在 Python 类中定义的正确方法是什么。示例:

class A:

    def fun1(self):
        pass

def fun2():
    pass

我想区分 A.fun1 是在类中定义的,而 fun2 不是。

解决方法

您可以使用属性 __qualname__(在 PEP 3155 中定义)并检查它是否包含 .,这表明该对象是在嵌套作用域中定义的。请注意,这也适用于在其他函数中定义的函数,因此在这个意义上它可能会给您误报。

>>> def test(): ...
... 
>>> test.__qualname__
'test'
>>> class Foo:
...     def test(self): ...
... 
>>> Foo.test.__qualname__
'Foo.test'
>>> def f():
...     def g(): ...
...     return g
... 
>>> f().__qualname__
'f.<locals>.g'
,

给你hasattr()

>>> hasattr(A,'fun1')
>>> True

>>> hasattr(A,'fun2')
>>> False