2022-07-03 18:21:15 +00:00
|
|
|
#![cfg(all(feature = "macros", not(PyPy)))]
|
|
|
|
|
2023-09-10 13:51:19 +00:00
|
|
|
use pyo3::{prelude::*, types::PySuper};
|
2022-07-03 18:21:15 +00:00
|
|
|
|
|
|
|
#[pyclass(subclass)]
|
|
|
|
struct BaseClass {
|
|
|
|
val1: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pymethods]
|
|
|
|
impl BaseClass {
|
|
|
|
#[new]
|
|
|
|
fn new() -> Self {
|
|
|
|
BaseClass { val1: 10 }
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn method(&self) -> usize {
|
|
|
|
self.val1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pyclass(extends=BaseClass)]
|
|
|
|
struct SubClass {}
|
|
|
|
|
|
|
|
#[pymethods]
|
|
|
|
impl SubClass {
|
|
|
|
#[new]
|
|
|
|
fn new() -> (Self, BaseClass) {
|
|
|
|
(SubClass {}, BaseClass::new())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn method(self_: &PyCell<Self>) -> PyResult<&PyAny> {
|
|
|
|
let super_ = self_.py_super()?;
|
|
|
|
super_.call_method("method", (), None)
|
|
|
|
}
|
2023-09-10 13:51:19 +00:00
|
|
|
|
|
|
|
fn method_super_new(self_: &PyCell<Self>) -> PyResult<&PyAny> {
|
|
|
|
let super_ = PySuper::new(self_.get_type(), self_)?;
|
|
|
|
super_.call_method("method", (), None)
|
|
|
|
}
|
2022-07-03 18:21:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_call_super_method() {
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let cls = py.get_type::<SubClass>();
|
|
|
|
pyo3::py_run!(
|
|
|
|
py,
|
|
|
|
cls,
|
|
|
|
r#"
|
|
|
|
obj = cls()
|
|
|
|
assert obj.method() == 10
|
2023-09-10 13:51:19 +00:00
|
|
|
assert obj.method_super_new() == 10
|
2022-07-03 18:21:15 +00:00
|
|
|
"#
|
|
|
|
)
|
|
|
|
});
|
|
|
|
}
|