我正在使用 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/