感谢您花时间阅读本文。希望你在这些陌生的时刻一切都好。
我正在实现一个类并开始研究如何为其属性提供自动完成功能。
从我的在线研究中,我得出的结论是 ipython 补全来自 __dir__
方法。
__getattr__
通常在您访问不存在的属性时调用。在我的项目中,如果发生这种情况,将运行一个需要一段时间的操作。为什么 ipython 尝试访问属性而不是仅仅显示 __dir__
返回的内容?
在单元格 2 中,我在点后点击 Tab 键以要求完成。
最佳答案
我认为问题在于您需要一个类的实例。这些方法是实例方法。
我添加了日志记录以便于调试。我在 ipython
中得到输出当我 example.something
时控制台或 example.<tab>
.
- Python 版本 3.8.2
- IPython 版本 7.14.0
这是我的观察:关于 <tab>
__dir__
被调用,返回的项目集合显示在 IPython 控制台中。如果在<tab>
之后选择的项目不是对象的属性,则 __getattr__
被调用以尝试查找它。
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class Example:
def __init__(self):
logging.info("init")
self._attrs = ("foo", "bar", "baz")
for attr in self._attrs:
setattr(self, attr, attr)
def __getattr__(self, attr):
logging.info(f"__getattr__ called: {attr}")
def __dir__(self):
logging.info("__dir__ called")
return ("extra", *self._attrs)
# Create an instance of Example.
# The instance methods can then be called on the instance.
example = Example()
if __name__ == "__main__":
logging.info(example)
关于python - IPython 自动完成调用 __getattr__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61597060/