Struct pyo3::pycell::PyRef [−][src]
pub struct PyRef<'p, T: PyClass> { /* fields omitted */ }
Expand description
Wraps a borrowed reference to a value in a PyCell<T>
.
See the PyCell
documentation for more.
Example
You can use PyRef
as an alternative of &self
receiver when
- You need to access the pointer of
PyCell
. - You want to get super class.
#[pyclass(subclass)]
struct Parent {
basename: &'static str,
}
#[pyclass(extends=Parent)]
struct Child {
name: &'static str,
}
#[pymethods]
impl Child {
#[new]
fn new() -> (Self, Parent) {
(Child { name: "Caterpillar" }, Parent { basename: "Butterfly" })
}
fn format(slf: PyRef<Self>) -> String {
// We can get *mut ffi::PyObject from PyRef
use pyo3::AsPyPointer;
let refcnt = unsafe { pyo3::ffi::Py_REFCNT(slf.as_ptr()) };
// We can get &Self::BaseType by as_ref
let basename = slf.as_ref().basename;
format!("{}(base: {}, cnt: {})", slf.name, basename, refcnt)
}
}
Implementations
impl<'p, T, U> PyRef<'p, T> where
T: PyClass + PyTypeInfo<BaseType = U, BaseLayout = PyCellInner<U>>,
U: PyClass,
impl<'p, T, U> PyRef<'p, T> where
T: PyClass + PyTypeInfo<BaseType = U, BaseLayout = PyCellInner<U>>,
U: PyClass,
Get PyRef<T::BaseType>
.
You can use this method to get super class of super class.
Examples
#[pyclass(subclass)]
struct Base1 {
name1: &'static str,
}
#[pyclass(extends=Base1, subclass)]
struct Base2 {
name2: &'static str,
}
#[pyclass(extends=Base2)]
struct Sub {
name3: &'static str,
}
#[pymethods]
impl Sub {
#[new]
fn new() -> PyClassInitializer<Self> {
PyClassInitializer::from(Base1{ name1: "base1" })
.add_subclass(Base2 { name2: "base2" })
.add_subclass(Self { name3: "sub" })
}
fn name(slf: PyRef<Self>) -> String {
let subname = slf.name3;
let super_ = slf.into_super();
format!("{} {} {}", super_.as_ref().name1, super_.name2, subname)
}
}