获取CPython中类方法的列表

2024-06-26 14:46:37 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我在python中定义了一个类,如下所示

class A(object):
    def __init__(self):
        pass
    def rockabye(self):
        pass

class B(A):
    def __init__(self):
        pass
    def iamOnlyinB(self):
        pass

我试图得到一个只存在于B中而不是从Aobject继承的函数列表。你知道吗

PyTypeObject* l_typeObject = <a function out of scope of the question>

for (int i = 0; true; i++)
    {
        PyMethodDef method_def = l_typeObject->tp_methods[i];
        if(method_def.ml_name == NULL)
            break;
        std::cout << method_def.ml_name <<std::endl;

    }

我总是发现l_typeObject->tp_methods就是NULL。为什么?有哪些可能的替代方法?你知道吗


Tags: ofnameselfobjectinitdefpassnull
1条回答
网友
1楼 · 发布于 2024-06-26 14:46:37

^{}是:

An optional pointer to a static NULL-terminated array of PyMethodDef structures, declaring regular methods of this type.

For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a method descriptor.

This field is not inherited by subtypes (methods are inherited through a different mechanism).

换句话说,这些是创建类的扩展模块附加到类的内置方法。你知道吗

对于在Python中构建的类,没有内置方法,也没有创建它的扩展模块,因此它总是NULL或空的。你知道吗


您要做的与在Python中做的相同:

  • 查看类的dict(可以通过^{}访问),或者
  • 调用dirinspect.getmembers之类的方法(与调用任何其他Python代码的方式相同)。你知道吗

当然,这会得到类的所有属性(取决于所做的操作,也可能是继承的所有属性),因此如果只需要方法,就需要对其进行过滤。但是您也可以使用与Python相同的方法来执行此操作。你知道吗

因为“method”是一个模棱两可的术语(它应该包括classmethods和staticmethods吗?当作为方法绑定时,包装器的行为就像函数一样,但不是函数呢?以此类推……,您需要准确地提出要过滤的规则,并以与Python相同的方式应用它。(一些东西,如^{},有特殊的C API支持;对于其他东西,您将执行子类检查或调用Python函数。)

相关问题 更多 >