PyO3 calling class method in instance method

I am using PyO3 to create Python bindings for some functionality. I have a Python module that exposes a single class. The class has two functions: one class function and one instance function. I would like to call the class function from the instance function, but can not figure out how to do this.

use pyo3::prelude::*;

#[pyclass]
struct MyClass {
    num: i32,
}

#[pymethods]
impl MyClass {
    #[new]
    fn py_new() -> Self {
        let num;
        if Self::is_true() {
            num = 0;
        } else {
            num = 1;
        }

        Self {
            num
        }
    }

    #[classmethod]
    fn is_true(cls: &PyType) -> bool {
        true
    }
}

#[pymodule]
fn my_package(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<MyClass>()?;
    Ok(())
}

The MyClass::is_true class method requires that the class be passed as the first argument, but I don't know how to do this from within the implementation of the MyClass::py_new method.

You can use the provided <Self as PyTypeInfo>::type_object() function to get a &PyType corresponding to Self:

use pyo3::{prelude::*, types::PyType, PyTypeInfo};

#[pyclass]
struct MyClass {
    num: i32,
}

#[pymethods]
impl MyClass {
    #[new]
    fn py_new(py: Python<'_>) -> Self {
        let num;
        if Self::is_true(Self::type_object(py)) {
            num = 0;
        } else {
            num = 1;
        }

        Self { num }
    }

    #[classmethod]
    fn is_true(cls: &PyType) -> bool {
        true
    }
}

#[pymodule]
fn my_package(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<MyClass>()?;
    Ok(())
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.