Skip to main content
 首页 » 编程设计

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

2025年05月04日12mayingbao

类的 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'] 

请您参考如下方法:

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