Constructing our own custom Python objects in Rust
In this final section, we will build a Python module in Rust that can be interacted with in the Python system as if it were a native Python object. To do this, we must follow these steps:
- Define a Python class with all our attributes.
- Define class static methods to process numbers.
- Define a class constructor.
Defining a Python class with the required attributes
To start our journey, we define our class in the src/class_module/fib_processor.rs
file, as follows:
- To build our class, we need to import the required macros by running the following code:
use pyo3::prelude::{pyclass, pymethods, staticmethod}; use crate::fib_calcs::fib_number::fibonacci_number; use crate::fib_calcs::fib_numbers::fibonacci_numbers;
Here, we are using the
pyclass
macro to define our Rust Python class. We then usepymethods
andstaticmethod
to define methods attached to the class. We also use standard Fibonacci numbers to calculate...