gpt4 book ai didi

python - 在 Python : Does it need to return a list and does the list need to be sorted? 中实现 `__dir__`

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:07 25 4
gpt4 key购买 nike

我有一个实现 __dir__ 方法的类。但是,我并不完全确定 dir API 的一些细节。

A:__dir__ 是否真的需要返回一个列表?我的实现是使用 set 来避免两次列出属性,我需要在返回之前将其转换为列表吗?来自documentation我猜它必须是一个列表:

If the object has a method named dir(), this method will be called and must return the list of attributes.

但是,在某些时候不返回列表会破坏功能吗?


B:结果需要排序吗?文档在这里有点模棱两可:

The resulting list is sorted alphabetically.

这是否意味着调用内置的 dir 会自动对 __dir__ 返回的数据进行排序,或者这是否意味着 dir 期望来自 __dir__?

编辑:顺便说一句,我的问题包括 Python 2(2.6 和 2.7)和 3(3.3、3.4)。

最佳答案

在 Python 2.7.3 下,答案是:

答:对,必须是列表:

>>> class F:
... def __dir__(self):
... return set(['1'])
...
>>> dir(F())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __dir__() must return a list, not set

B:不,dir 会对其进行排序。

>>> class G:
... def __dir__(self):
... return ['c','b','a']
...
>>> dir(G())
['a', 'b', 'c']

关于python - 在 Python : Does it need to return a list and does the list need to be sorted? 中实现 `__dir__`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29393542/

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