我有一个使用pyo3 pyclass宏的rust结构,以允许在python中使用。这对于简单的结构很好用,但是如果我的结构包含来自不同库的类型,则将变得更加困难。
例子:
use geo::Point;
#[pyclass]
#[derive(Clone, Copy)]
pub struct CellState {
pub id: u32,
pub position: Point<f64>,
pub population: u32,
}
在上面,我们使用rust地理库中的Point类型。编译器提供以下错误:the trait `pyo3::PyClass` is not implemented for `geo::Point<f64>
如果然后尝试在Point上实现PyClass:impl PyClass for Point<f64> {}
它给了我下面的编译器错误:impl doesn't use only types from inside the current crate
有任何干净,简单的方法解决此问题的想法吗?
最佳答案
在找到更好的答案之前,我的解决方案是将类嵌套在python类中,但随后我不得不手动编写getter和setter。
#[pyclass]
#[derive(Clone)]
pub struct CellStatePy {
pub inner: CellState,
}
#[pymethods]
impl CellStatePy {
#[new]
pub fn new(id: u32, pos: (f64, f64), population: u32) -> Self {
CellStatePy {
inner: CellState {
id: CellIndex(id),
position: point!(x: pos.0, y: pos.1),
population,
},
}
}
}
然后实现PyObjectProtocol:#[pyproto]
impl PyObjectProtocol for CellStatePy {
fn __str__(&self) -> PyResult<&'static str> {
Ok("CellStatePy")
}
fn __repr__<'a>(&'a self) -> PyResult<String> {
Ok(format!("CellStateObj id: {:?}", self.inner.id))
}
fn __getattr__(&'a self, name: &str) -> PyResult<String> {
let out: String = match name {
"id" => self.inner.id.into(),
"position" => format!("{},{}", self.inner.position.x(), self.inner.position.y()),
"population" => format!("{}", self.inner.population),
&_ => "INVALID FIELD".to_owned(),
};
Ok(out)
}
}
关于python - 在包含来自不同 crate 的类型的使用rust 结构上使用pyo3 pyclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65393247/