python - python swig 中的 repr 函数

标签 python swig

我有一个 Swig 包装器可以在 python 中使用。 对于我的一个类(class),我创建了一个 repr 函数,如下所示

%module myModule
%{
    #include <string>
    #include <sstream>
%}

%extend myClass {
std::string __repr__()
{
    std::ostringstream ss;
    ss << "MyClass(attr1=" << $self->attr1 << ", attr2=" << $self->attr1 << ")";

    return ss.str();
}}

但是,当我编译包装器并在 python 中使用它时,出现以下错误 __repr__ 返回非字符串(类型 SwigPyObject)

我该如何解决这个问题?

最佳答案

这是我在独立 SWIG 接口(interface)文件中的问题中评论的工作示例。如前所述,您需要包含 SWIG 的 std_string.i 支持接口(interface):

示例.i

%module example

%{
#include <string>
#include <sstream>
%}

%include <std_string.i>

// Filling in missing minimal class definition.
%inline %{
class myClass {
public:
    int attr1;
    int attr2;
    myClass(int a1, int a2) : attr1(a1), attr2(a2) {}
};
%}

%extend myClass {
std::string __repr__()
{
    std::ostringstream ss;
    ss << "MyClass(attr1=" << $self->attr1 << ", attr2=" << $self->attr1 << ")";

    return ss.str();
}
}

演示:

>>> import example as e
>>> m = e.myClass(5,7)
>>> m
MyClass(attr1=5, attr2=5)

关于python - python swig 中的 repr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74853917/

相关文章:

python - 如何替换 pandas 数据框中看起来相似的值?

python - 在继续之前检查文件列表是否存在?

python - 使用 Python 解析 CSV/制表符分隔的 txt 文件

python - SWIG C++/Python:如何处理抽象类的shared_ptr的std::map

swig - 如何在 Linux centos 上安装 SWIG

python - 将我自己的 get/set C++ 成员函数视为 SWIG 中的成员变量?

c++ - 如何检查 SWIG 接口(interface)文件中的 Lua 版本?

python - 对象在集合操作中的行为

c - Swig:输入中的语法错误(3)

python - 属性错误: 'str' object has no attribute 'pop'