感谢您抽出宝贵的时间阅读本文档。希望在这个陌生的时代一切都好。
我正在实现一个类,并开始研究如何在其属性上提供自动完成功能。通过我的在线研究,我得出的结论是ipython补全来自__dir__
方法。
__getattr__
通常在您访问不存在的属性时调用。在我的项目中,如果发生这种情况,则需要一段时间。为什么ipython尝试访问属性而不是仅显示返回的__dir__
?
from time import sleep
class example:
def __getattr__(self, attr):
if attr == 'test':
sleep(2)
def __dir__(self):
return ["test"]
example. # press tab for auto complete
需要2秒。为什么会这样呢?自动完成功能应仅调用__dir__
,但也应调用__getattr__
。谢谢您的宝贵时间,请注意安全!
我认为问题是您需要一个类的实例。这些方法是实例方法。
class Example:
def __init__(self):
# Set some arbitrary attributes on the instance.
self.bar = "bar"
self.baz = "baz"
def __getattr__(self, attr):
# print is a more reliable indication that the
# method was called. sleep was probably perceived but not
# happening.
print(f"__getattr__ called: {attr}")
# prevent recursion by using the __getattribute__ on parent.
return super().__getattribute__(attr)
def __dir__(self):
# This seems to be the method called when tab key is hit.
return ["footest"]
# Create an instance of Example.
# The instance methods can then be called on the instance.
example = Example()
example.bar
example.<tab> # "footest" displayed