Update class.md - add example of `new` returning a `PyResult` (#1688)

* Update class.md - add example of `new` returning a `PyResult`

* Update class.md
This commit is contained in:
Aviram Hassan 2021-06-23 12:40:01 +03:00 committed by GitHub
parent dc66afa159
commit 13cd092c4e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 17 additions and 0 deletions

View File

@ -169,6 +169,23 @@ impl MyClass {
}
```
Alternatively, if your `new` method may fail you can return `PyResult<Self>`.
```rust
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {
num: i32,
}
#[pymethods]
impl MyClass {
#[new]
fn new(num: i32) -> PyResult<Self> {
Ok(MyClass { num })
}
}
```
If no method marked with `#[new]` is declared, object instances can only be
created from Rust, but not from Python.