我在 Rust PyO3 扩展中定义了以下类结构:
#[pyclass(subclass)]
struct Parent {
foo: i32
}
#[pyclass(extends=Parent)]
struct Child {
bar: i32
}
然后在Python中,一个纯Python类包含一个属性,它可以是父类或子类的实例,如下所示:
class MyOtherClass:
def __init__(self):
# This attribute can be an instance of Parent or Child
self.rust_class = Parent(foo=5)
然后在另一个 PyO3 函数中,我希望能够获取
MyOtherClass.rust_class
属性的 Rust 结构。我可以很容易地得到一个,比如通过执行下面的函数,但是我如何能够根据属性的实例来检索子结构的父结构?
#[pyfunction]
fn my_function(
my_other_class: &PyAny //This is an instance of MyOtherClass
) -> i32 {
let my_struct: Parent = my_other_class.getattr("rust_class").unwrap().extract().unwrap();
my_struct.foo
}
PyO3 已经发生了很大的变化(引入了新的
Bound
API),但基本思想是相同的:尝试强制转换为 Child
,如果失败,则强制转换为 Parent
:
/// Formats the sum of two numbers as string.
#[pyfunction]
fn my_function(my_other_class: &Bound<'_, PyAny>) -> PyResult<i32> {
let my_struct = my_other_class.getattr("rust_class")?;
let parent = my_struct.downcast::<Parent>()?;
let mut sum = parent.borrow().foo;
if let Ok(child) = parent.downcast::<Child>() {
sum += child.borrow().bar;
}
Ok(sum)
}