1 | use crate::ffi; |
2 | use crate::types::PyType; |
3 | use crate::{PyAny, PyResult}; |
4 | |
5 | /// Represents a Python `super` object. |
6 | /// |
7 | /// This type is immutable. |
8 | #[repr (transparent)] |
9 | pub struct PySuper(PyAny); |
10 | |
11 | pyobject_native_type_core!( |
12 | PySuper, |
13 | pyobject_native_static_type_object!(ffi::PySuper_Type) |
14 | ); |
15 | |
16 | impl PySuper { |
17 | /// Constructs a new super object. More read about super object: [docs](https://docs.python.org/3/library/functions.html#super) |
18 | /// |
19 | /// # Examples |
20 | /// |
21 | /// ```rust |
22 | /// use pyo3::prelude::*; |
23 | /// |
24 | /// #[pyclass(subclass)] |
25 | /// struct BaseClass { |
26 | /// val1: usize, |
27 | /// } |
28 | /// |
29 | /// #[pymethods] |
30 | /// impl BaseClass { |
31 | /// #[new] |
32 | /// fn new() -> Self { |
33 | /// BaseClass { val1: 10 } |
34 | /// } |
35 | /// |
36 | /// pub fn method(&self) -> usize { |
37 | /// self.val1 |
38 | /// } |
39 | /// } |
40 | /// |
41 | /// #[pyclass(extends=BaseClass)] |
42 | /// struct SubClass {} |
43 | /// |
44 | /// #[pymethods] |
45 | /// impl SubClass { |
46 | /// #[new] |
47 | /// fn new() -> (Self, BaseClass) { |
48 | /// (SubClass {}, BaseClass::new()) |
49 | /// } |
50 | /// |
51 | /// fn method(self_: &PyCell<Self>) -> PyResult<&PyAny> { |
52 | /// let super_ = self_.py_super()?; |
53 | /// super_.call_method("method" , (), None) |
54 | /// } |
55 | /// } |
56 | /// ``` |
57 | pub fn new<'py>(ty: &'py PyType, obj: &'py PyAny) -> PyResult<&'py PySuper> { |
58 | let py = ty.py(); |
59 | let super_ = py.get_type::<PySuper>().call1((ty, obj))?; |
60 | let super_ = super_.downcast::<PySuper>()?; |
61 | Ok(super_) |
62 | } |
63 | } |
64 | |