2018-05-02 18:49:40 +00:00
|
|
|
use pyo3::prelude::*;
|
|
|
|
use std::isize;
|
|
|
|
|
|
|
|
#[macro_use]
|
|
|
|
mod common;
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-05-02 18:49:40 +00:00
|
|
|
struct ClassWithProperties {
|
|
|
|
num: i32,
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pymethods]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl ClassWithProperties {
|
|
|
|
fn get_num(&self) -> PyResult<i32> {
|
|
|
|
Ok(self.num)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[getter(DATA)]
|
|
|
|
fn get_data(&self) -> PyResult<i32> {
|
|
|
|
Ok(self.num)
|
|
|
|
}
|
|
|
|
#[setter(DATA)]
|
|
|
|
fn set_data(&mut self, value: i32) -> PyResult<()> {
|
|
|
|
self.num = value;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn class_with_properties() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-13 20:35:26 +00:00
|
|
|
let inst = Py::new(py, ClassWithProperties { num: 10 }).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
|
|
|
|
py_run!(py, inst, "assert inst.get_num() == 10");
|
|
|
|
py_run!(py, inst, "assert inst.get_num() == inst.DATA");
|
|
|
|
py_run!(py, inst, "inst.DATA = 20");
|
|
|
|
py_run!(py, inst, "assert inst.get_num() == 20");
|
|
|
|
py_run!(py, inst, "assert inst.get_num() == inst.DATA");
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-05-02 18:49:40 +00:00
|
|
|
struct GetterSetter {
|
2019-02-18 19:07:41 +00:00
|
|
|
#[pyo3(get, set)]
|
2018-05-02 18:49:40 +00:00
|
|
|
num: i32,
|
2019-02-18 19:07:41 +00:00
|
|
|
#[pyo3(get, set)]
|
2018-06-12 15:47:24 +00:00
|
|
|
text: String,
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pymethods]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl GetterSetter {
|
|
|
|
fn get_num2(&self) -> PyResult<i32> {
|
|
|
|
Ok(self.num)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn getter_setter_autogen() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-13 20:35:26 +00:00
|
|
|
let inst = Py::new(
|
|
|
|
py,
|
|
|
|
GetterSetter {
|
2018-06-15 19:21:12 +00:00
|
|
|
num: 10,
|
|
|
|
text: "Hello".to_string(),
|
2019-02-13 20:35:26 +00:00
|
|
|
},
|
|
|
|
)
|
|
|
|
.unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
|
|
|
|
py_run!(py, inst, "assert inst.num == 10");
|
|
|
|
py_run!(py, inst, "inst.num = 20; assert inst.num == 20");
|
2018-06-15 19:21:12 +00:00
|
|
|
py_run!(
|
|
|
|
py,
|
|
|
|
inst,
|
|
|
|
"assert inst.text == 'Hello'; inst.text = 'There'; assert inst.text == 'There'"
|
|
|
|
);
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|