python的dir()函数的结果顺序

时间:2012-03-11 22:08:00

标签: python

可以通过创建一个返回用户定义列表的特殊函数来自定义类的dir(),那么为什么它不能维护我指定的顺序呢?这是一个例子:

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

为什么dir()似乎对我的列表进行排序并返回['a', 'b', 'c']而不是['a', 'c', 'b']

奇怪(对我来说),直接调用成员函数会得到预期的结果:

>>> c.__dir__()
['a', 'c', 'b']

2 个答案:

答案 0 :(得分:6)

这是dir()内置的定义。它明确地按字母顺序排列名称列表:

Help on built-in function dir in module __builtin__:

dir(...)
   dir([object]) -> list of strings

   If called without an argument, return the names in the current scope.
   Else, return an alphabetized list of names comprising (some of) the attributes
   of the given object, and of attributes reachable from it.
   If the object supplies a method named __dir__, it will be used; otherwise
   the default dir() logic is used and returns:
     for a module object: the module's attributes.
     for a class object:  its attributes, and recursively the attributes
       of its bases.
     for any other object: its attributes, its class's attributes, and
       recursively the attributes of its class's base classes.

答案 1 :(得分:1)

documentation of the dir function说:

  

结果列表按字母顺序排序。

相关问题