Skip to main content
 首页 » 编程设计

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

2025年05月04日14soundcode

我有一个实现 __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']