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

标签 python

来自 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/

相关文章:

python - ssh 到 linux 服务器,不使用 ps 命令从 python 列出 PID

python - 从分发邮件 ID [Python] 发送邮件的问题

python - 使用 argparse (python) 创建变量键/值对

python - 如何将没有数字字符的字母字符与 Python 正则表达式匹配?

python - 无法在 Windows 上使用 git-p4 导入

python - GAE 中应该使用什么来存储数据?

Python 守护进程不会在 Ubuntu 的后台运行

python - Python 单元测试中是否有针对子列表的断言?

Python 列表理解中的一项出现不需要的 UnicodeDecodeError 异常

python - 寻找最接近值算法