2012-03-11 46 views
1

类的dir()可以通过创建一个返回用户定义列表的特殊函数来定制,那为什么它不维护我指定的顺序?这里有一个例子: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'] 

回答

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. 
+0

而且他们说没有愚蠢的问题......无论如何,感谢至少证明我没有想象的东西。猜猜下次我应该rtm。再次感谢您的答复。 – zenzic 2012-03-11 22:52:59