guide: fix duplicated example for #[new]
The second one was probably intended to show a fallible `#[new]`. Also show that the method does not need to be named `new()`, which is nice because `new()` can be used for a Rust-level constructor if they differ.
This commit is contained in:
parent
754edea81e
commit
f084ceb9b1
|
@ -78,18 +78,26 @@ Alternatively, if your `new` method may fail you can return `PyResult<Self>`.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
# use pyo3::prelude::*;
|
# use pyo3::prelude::*;
|
||||||
|
# use pyo3::exceptions::PyValueError;
|
||||||
# #[pyclass]
|
# #[pyclass]
|
||||||
# struct Number(i32);
|
# struct Nonzero(i32);
|
||||||
#
|
#
|
||||||
#[pymethods]
|
#[pymethods]
|
||||||
impl Number {
|
impl Nonzero {
|
||||||
#[new]
|
#[new]
|
||||||
fn new(value: i32) -> Self {
|
fn py_new(value: i32) -> PyResult<Self> {
|
||||||
Number(value)
|
if value == 0 {
|
||||||
|
Err(PyValueError::new_err("cannot be zero"))
|
||||||
|
} else {
|
||||||
|
Ok(Nonzero(value))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
As you can see, the Rust method name is not important here; this way you can
|
||||||
|
still use `new()` for a Rust-level constructor.
|
||||||
|
|
||||||
If no method marked with `#[new]` is declared, object instances can only be
|
If no method marked with `#[new]` is declared, object instances can only be
|
||||||
created from Rust, but not from Python.
|
created from Rust, but not from Python.
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue