gpt4 book ai didi

python - IPython 自动完成调用 __getattr__

转载 作者:行者123 更新时间:2023-12-05 06:17:35 24 4
gpt4 key购买 nike

感谢您花时间阅读本文。希望你在这些陌生的时刻一切都好。

我正在实现一个类并开始研究如何为其属性提供自动完成功能。从我的在线研究中,我得出的结论是 ipython 补全来自 __dir__ 方法。

__getattr__ 通常在您访问不存在的属性时调用。在我的项目中,如果发生这种情况,将运行一个需要一段时间的操作。为什么 ipython 尝试访问属性而不是仅仅显示 __dir__ 返回的内容?

在单元格 2 中,我在点后点击 Tab 键以要求完成。

enter image description here

最佳答案

我认为问题在于您需要一个类的实例。这些方法是实例方法。

我添加了日志记录以便于调试。我在 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)

enter image description here

关于python - IPython 自动完成调用 __getattr__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61597060/

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