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

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

How to add private methods to pyo3 pymethods?

问题

  1. #[pyclass]
  2. pub struct SomeItem;
  3. #[pymethods]
  4. impl SomeItem {
  5. #[new]
  6. pub fn new() -> Self { // visible for python constructor
  7. SomeItem;
  8. }
  9. pub fn method(&self) -> u8 { // visible for python method
  10. self.hidden_method()
  11. }
  12. #[pyo3(ignore)] // just for example
  13. fn hidden_method(&self) -> u8 { // invisible for python method (that must be able to return non-python type)
  14. 0
  15. }
  16. }
英文:

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

Example:

  1. #[pyclass]
  2. pub struct SomeItem;
  3. #[pymethods]
  4. impl SomeItem {
  5. #[new]
  6. pub fn new() -> Self { // visible for python constructor
  7. SomeItem;
  8. }
  9. pub fn method(&self) -> u8 { // visible for python method
  10. self.hidden_method()
  11. }
  12. #[pyo3(ignore)] // just for example
  13. fn hidden_method(&self) -> u8 { // invisible for python method (that must be able to return non-python type)
  14. 0
  15. }
  16. }

答案1

得分: 1

关于使用单独的 impl 块呢?

  1. #[pymethods]
  2. impl SomeItem {
  3. #[new]
  4. pub fn new() -> Self { // 对Python构造函数可见
  5. SomeItem;
  6. }
  7. pub fn method(&self) -> u8 { // 对Python方法可见
  8. self.hidden_method()
  9. }
  10. }
  11. impl SomeItem {
  12. fn hidden_method(&self) -> u8 {
  13. 0
  14. }
  15. }
英文:

What about using a separate impl block?

  1. #[pymethods]
  2. impl SomeItem {
  3. #[new]
  4. pub fn new() -> Self { // visible for python constructor
  5. SomeItem;
  6. }
  7. pub fn method(&self) -> u8 { // visible for python method
  8. self.hidden_method()
  9. }
  10. }
  11. impl SomeItem {
  12. fn hidden_method(&self) -> u8 {
  13. 0
  14. }
  15. }

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:

确定