如何将私有方法添加到 pyo3 pymethods?

huangapple go评论64阅读模式
英文:

How to add private methods to pyo3 pymethods?

问题

#[pyclass]
pub struct SomeItem;

#[pymethods]
impl SomeItem {
    #[new]
    pub fn new() -> Self {  // visible for python constructor
        SomeItem;
    }

    pub fn method(&self) -> u8 {  // visible for python method
        self.hidden_method()
    }

    #[pyo3(ignore)]  // just for example
    fn hidden_method(&self) -> u8 {  // invisible for python method (that must be able to return non-python type)
        0
    }
}
英文:

I'd like to add hidden methods to pyo3 class methods implementation which will be invisible for Python.

Example:

#[pyclass]
pub struct SomeItem;

#[pymethods]
impl SomeItem {
    #[new]
    pub fn new() -> Self {  // visible for python constructor
        SomeItem;
    }

    pub fn method(&self) -> u8 {  // visible for python method
        self.hidden_method()
    }

    #[pyo3(ignore)]  // just for example
    fn hidden_method(&self) -> u8 {  // invisible for python method (that must be able to return non-python type)
        0
    }
}

答案1

得分: 1

关于使用单独的 impl 块呢?

#[pymethods]
impl SomeItem {
    #[new]
    pub fn new() -> Self {  // 对Python构造函数可见
        SomeItem;
    }

    pub fn method(&self) -> u8 {  // 对Python方法可见
        self.hidden_method()
    }
}

impl SomeItem {
    fn hidden_method(&self) -> u8 {
        0
    }
}
英文:

What about using a separate impl block?

#[pymethods]
impl SomeItem {
    #[new]
    pub fn new() -> Self {  // visible for python constructor
        SomeItem;
    }

    pub fn method(&self) -> u8 {  // visible for python method
        self.hidden_method()
    }
}

impl SomeItem {
    fn hidden_method(&self) -> u8 {
        0
    }
}

huangapple
  • 本文由 发表于 2023年5月11日 04:19:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定