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

zen*_*zic 1 python

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

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

为什么dir()看似排序我的清单并返回['a', 'b', 'c']而不是['a', 'c', 'b']

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

>>> c.__dir__()
['a', 'c', 'b']
Run Code Online (Sandbox Code Playgroud)

Jam*_*ett 7

这是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.