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

関連する問題