小编fds*_*dsa的帖子

使用 pyo3 从 rust 移植到 python 的类的 __str__ 函数未用于打印

我正在使用pyo3rust crate (version 0.11.1) 以便将 rust 代码移植到 cpython (version 3.8.2) 代码中。我创建了一个名为类my_class,定义了以下功能:new__str__,和__repr__

TL;DR:该__str__函数存在于使用 pyo3 crate 从 rust 移植的类上,但在使用时不会打印print(obj),而是必须编写print(obj.__str__())

my_class定义是在这里:

use pyo3::prelude::*;

#[pyclass]
struct my_class {
    #[pyo3(get, set)]
    num: i32,
    #[pyo3(get, set)]
    debug: bool,
}

#[pymethods]
impl my_class {
    #[new]
    fn new(num: i32, debug: bool) -> Self {
        my_class {num, debug}
    }
    fn __str__(&self) -> PyResult<String>   {
        Ok(format!("[__str__] Num: {}, Debug: {}", …
Run Code Online (Sandbox Code Playgroud)

python cpython object rust

11
推荐指数
1
解决办法
456
查看次数

标签 统计

cpython ×1

object ×1

python ×1

rust ×1