gpt4 book ai didi

python - 为什么 ' dir(1) is dir(True) ' 返回 False

转载 作者:行者123 更新时间:2023-11-28 21:09:55 25 4
gpt4 key购买 nike

来自 this奎斯顿的回答

is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

dir(1)dir(True) 不是指向同一个对象吗?它们都打印了相同方法的列表。我是否遗漏了一些有关 object 的信息?

>>> dir(1) == dir(True)
True
>>> dir(1) is dir(True)
False
>>>

最佳答案

首先,True 不是1:

>>> True is not 1
True

其次,作为documentation

dir([object])

[...] With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

The resulting list is sorted alphabetically. [...]


现在,intbool 都有从 object.__dir__ 填充的 __dir__ 槽:

>>> int.__dir__
<method '__dir__' of 'object' objects>
>>> bool.__dir__
<method '__dir__' of 'object' objects>

以及 object.__dir__ 的文档添加这一额外信息:

object.__dir__(self)

Called when dir() is called on the object. A sequence must be returned. dir() converts the returned sequence to a list and sorts it.

如文档所述,dir每次调用 构造一个 列表,然后对其进行排序。 (我们还可以查看 _dir_object 的代码,它在 __dir__ 的返回值上调用 PySequence_ListPySequence_List 将一个序列作为参数,并返回一个 < em>new 列表,其元素与原始序列相同;这个新创建的列表然后是 sortedreturned )

>>> a = 1
>>> dir(a) is dir(a)
False

第三,Truebool类型的一个实例,它是int的子类。

 >>> isinstance(True, bool)
True
>>> isinstance(1, int)
True
>>> issubclass(bool, int)
True
>>> isinstance(True, int)
True

此外,bool 不会添加任何 int 中不存在的方法。因为结果列表是按字母顺序排序的,

>>> dir(1) == dir(True)
True

关于python - 为什么 ' dir(1) is dir(True) ' 返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37374629/

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