如何使用PyO3调用等价于`object.__getattribute__(self, name)`的方法?
如何在PyO3中调用等价于Python的
object.__getattribute__(self, name)的方法 当你在PyO3中自定义__getattribute__方法时,直接调用当前实例的该方法会触发递归(因为会调用你自己实现的版本)。正确的做法是显式调用基类object的原生__getattribute__方法,具体实现如下:
use pyo3::{prelude::*, types::PyType}; #[pyclass] struct ClassWithGetAttribute; #[pymethods] impl ClassWithGetAttribute { fn __getattribute__(&self, name: &str, py: Python<'_>) -> PyResult<PyObject> { if name == "exists" { Ok(42.into_py(py)) } else { // 获取Python原生的object类型 let object_type = py.get_type::<PyType>().getattr("object")?; // 调用object.__getattribute__(self, name) object_type.call_method1("__getattribute__", (self, name)) } } }
关键说明:
- 必须在方法参数中加入
Python<'_>,用于获取Python运行时的上下文环境 - 通过
py.get_type::<PyType>().getattr("object")获取Python的原生object类,避免递归调用自定义的方法 - 使用
call_method1方法调用object类的__getattribute__,传入当前实例和目标属性名,这就等价于Python中object.__getattribute__(self, name)的行为
原来的写法错误在于直接调用实例自身的__getattribute__,会无限递归触发你自己定义的方法,无法调用到原生的实现。
内容的提问来源于stack exchange,提问作者Kaos
相关产品推荐
相关产品推荐

