gpt4 book ai didi

python - 使用pyo3从rust移植到python的类的__str__函数没有在打印中使用

转载 作者:行者123 更新时间:2023-12-03 11:23:26 33 4
gpt4 key购买 nike

我正在使用 pyo3 rust crate (版本 0.11.1 ) 以便将 rust 代码移植到 cpython (版本 3.8.2 ) 代码中。我创建了一个名为 my_class 的类并定义了以下函数:new , __str__ , 和 __repr__ .

TL;DR: The __str__ function exists on a class ported from rust using the pyo3 crate, but doesn't get printed when just using print(obj), and instead having to write 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: {}", self.num, self.debug))
}

fn __repr__(&self) -> PyResult<String> {
Ok(format!("[__repr__] Num: {}, Debug: {}", self.num, self.debug))
}
}

#[pymodule]
fn pymspdb(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<my_class>()?;
Ok(())
}
我构建它(进入 Release模式),并使用以下代码测试代码:
from my_module import my_class

def main():
dsa = my_class(1, True)
print(dsa)
print(dsa.__str__())


if __name__ == "__main__":
main()
运行测试 python 代码时,我得到以下输出:
<my_class object at 0x7fb7828ae950>
[__str__] Num: 1, Debug: true
现在我已经想到了可能的解决方案。一种解决方案可能是 pyo3 rust crate 实际上充当代理,并且为了将类移植到 python 中,可能会实现某种对象,将所有操作转移到移植的类。所以它可能不会实现自己的 __str__因此没有给我想要的东西。
我想到的第二种可能的解决方案是我可能不会重载 __str__正常运行,因此当 python 尝试使用 print 函数时,它不会访问正确的函数而只​​是执行默认行为。
感谢您到目前为止的阅读,希望我能找到答案,因为我没有在网上找到任何关于此的内容。

最佳答案

我很确定这是因为您需要通过 PyObjectProtocol trait 来实现这些方法。 .
许多 Python __magic__方法对应于 C 级 function pointer slots在类型对象的内存布局中。用 C 实现的类型需要在槽中提供函数指针,Python 会自动生成一个方法来包装指针以进行显式方法调用。在 Python 中实现的类型将自动插入代表魔术方法的函数指针。
Python 内部通常会寻找函数指针而不是相应的魔法方法,如果 Python 没有找到函数指针,它将表现得好像该方法不存在。这就是为什么,例如,您必须使用 #[new]标记你的构造函数而不是实现 __new__静态方法。__str____repr__也对应于函数指针 - 具体来说, tp_str tp_repr .如果您只是尝试将它们实现为常规方法,pyo3 将不会生成所需的函数指针。 PyObjectProtocol是为此要通过的pyo3接口(interface)。

关于python - 使用pyo3从rust移植到python的类的__str__函数没有在打印中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62666926/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com