gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:57 26 4
gpt4 key购买 nike

类的 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.

关于python - python 的 dir() 函数的结果顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com