diff --git a/guide/src/class.md b/guide/src/class.md index a186ee23cd6..366043b5b87 100644 --- a/guide/src/class.md +++ b/guide/src/class.md @@ -886,7 +886,7 @@ impl MyClass { ## Class attributes -To create a class attribute (also called [class variable][classattr]), a method without any arguments can be annotated with the `#[classattr]` attribute. +To create a class attribute (also called [class variable][classattr]), an associated constant can be annotated with the `#[classattr]` attribute. ```rust,no_run # use pyo3::prelude::*; @@ -895,25 +895,19 @@ To create a class attribute (also called [class variable][classattr]), a method #[pymethods] impl MyClass { #[classattr] - fn my_attribute() -> String { - "hello".to_string() - } + const MY_ATTRIBUTE: &'static str = "foobar"; } - -Python::attach(|py| { - let my_class = py.get_type::(); - pyo3::py_run!(py, my_class, "assert my_class.my_attribute == 'hello'") -}); +# +# Python::attach(|py| { +# let my_class = py.get_type::(); +# pyo3::py_run!(py, my_class, "assert my_class.MY_ATTRIBUTE == 'foobar'") +# }); ``` -> [!NOTE] -> If the method has a `Result` return type and returns an `Err`, PyO3 will panic during -class creation. +If `const` code is too limiting, a method without any arguments can be annotated with the `#[classattr]` attribute. > [!NOTE] -> `#[classattr]` does not work with [`#[pyo3(warn(...))]`](./function.md#warn) attribute. - -If the class attribute is defined with `const` code only, one can also annotate associated constants: +> Here too, the class attribute value is computed once during the class creation and not each time the attribute is accessed. ```rust,no_run # use pyo3::prelude::*; @@ -922,10 +916,24 @@ If the class attribute is defined with `const` code only, one can also annotate #[pymethods] impl MyClass { #[classattr] - const MY_CONST_ATTRIBUTE: &'static str = "foobar"; + fn my_attribute() -> String { + "hello".to_string() + } } +# +# Python::attach(|py| { +# let my_class = py.get_type::(); +# pyo3::py_run!(py, my_class, "assert my_class.my_attribute == 'hello'") +# }); ``` +> [!NOTE] +> If the method has a `Result` return type and returns an `Err`, PyO3 will panic during +class creation. + +> [!NOTE] +> `#[classattr]` does not work with [`#[pyo3(warn(...))]`](./function.md#warn) attribute. + ## Classes as function arguments Class objects can be used as arguments to `#[pyfunction]`s and `#[pymethods]` in the same way as the self parameters of instance methods, i.e. they can be passed as: