gpt4 book ai didi

python - PyO3 在 Rust 中实现 python 可迭代类

转载 作者:行者123 更新时间:2023-12-05 04:48:28 27 4
gpt4 key购买 nike

我已经 found example如何在 Rust 中实现 PyIterProtocol。

use pyo3::prelude::*;
use pyo3::PyIterProtocol;
use pyo3::class::iter::IterNextOutput;

#[pyclass]
struct Iter {
count: usize
}

#[pyproto]
impl PyIterProtocol for Iter {
fn __next__(mut slf: PyRefMut<Self>) -> IterNextOutput<usize, &'static str> {
if slf.count < 5 {
slf.count += 1;
IterNextOutput::Yield(slf.count)
} else {
IterNextOutput::Return("Ended")
}
}
}

但我不知道如何实现一个可迭代但本身不是迭代器的容器类。本质上,我希望能够像 Python 那样分解我的对象

x, y, z = my_object

最佳答案

来自 the user guide on Iterator Types :

In many cases you'll have a distinction between the type being iterated over (i.e. the iterable) and the iterator it provides. In this case, you should implement PyIterProtocol for both the iterable and the iterator, but the iterable only needs to support __iter__() while the iterator must support both __iter__() and __next__().

关于python - PyO3 在 Rust 中实现 python 可迭代类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68077858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com