Repository navigation
Get a pyclass from a pyclass with reference?
#2261
Replies: 1 comment 4 replies
#[pyclass]
struct Wallet {
pub cash: i64,
}
#[pymethods]
impl Wallet {
#[new]
fn new(cash: i64) -> Self {
Self { cash }
}
pub fn add_cash(&mut self, cash: i64) {
self.cash += cash;
}
}
#[pyclass]
struct Player {
pub name: String,
#[pyo3(get)]
pub wallet: Py<Wallet>,
}
#[pymethods]
impl Player {
#[new]
fn new(name: String, cash: i64, py: Python) -> Self {
Self {
name,
wallet: Py::new(py, Wallet { cash }).unwrap(),
}
}
} |
4 replies
Answer selected by
sun-rs
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have two
#[pyclass]and I combine one into another one like below:What I want to do is create a instance of
Playerin Python and call methods ofWalletlike:But I found everytime use
player.wallet, it would return a new clone for wallet with a new memory address(found by callid(wallet)).And because
player.walletneed to create new object, it takes more time.How to achieve
player.wallet.add_cash(10)in Python like Rust did (call its inner instance rather than a clone) ?All reactions