python - 查找成员函数是否存在于 Boost python::object 中

标签 python c++ boost boost-python

我正在使用 Boost Python 使 C++ 和 Python 一起运行,我有一个看起来像这样的代码,创建一个 python 对象的实例并调用它的一个成员函数。

bp::object myInstance;
// ... myInstance is initialized
bp::object fun = myInstance.attr("myfunction");
fun();

我想在调用之前检查成员函数是否存在。如果它不存在,我不想调用。

问题是:即使函数不存在,对 myInstance.attr("myfunction") 的调用也会成功。因此,测试该函数是否存在于我当前代码中的唯一方法是尝试调用它并捕获异常。

有没有办法在不涉及异常或不调用函数的情况下检查函数是否存在?

最佳答案

the call to myInstance.attr("myfunction") is successful even if the function does not exist

很确定它会抛出一个 AttributeError

Is there any way to check if the function exists without involving exception or calling the function?

Boost.Python 中的一个奇怪漏洞是它没有hasattr() 函数。很容易添加:

namespace boost { namespace python {
    bool hasattr(object o, const char* name) {
        return PyObject_HasAttrString(o.ptr(), name);
    }
} }

然后你就可以使用它了:

if (hasattr(myInstance, "myfunction")) {
    bp::object fun = myInstance.attr("myfunction");
    fun();
    // ...
}

关于python - 查找成员函数是否存在于 Boost python::object 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39924912/

相关文章:

python - Askbot - 没有名为 xdg.Config 的模块

python - 从嵌套列表的字典理解返回字典

python - 在python中按名称忽略忽略列表中的项目

c++ - IAT Hook 但未调用 Hook 函数

c++ - 写static const uint变量和匿名枚举变量有什么区别?

c++ - boost::stable_vector 的 capacity 成员函数不返回分配的容量

python - 如何获取元组的第一个元素与匹配的第二个元素(python)

c++ - 在 C++ 中的数组前添加 '++' 会发生什么?

c++ - Boost 目录迭代器 "no such file or directory"

c++ - 如何包含 Boost 库?