2012-03-11 82 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