来自 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 waydir()
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. [...]
现在,int
和 bool
都有从 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_List
;PySequence_List
将一个序列作为参数,并返回一个 < em>new 列表,其元素与原始序列相同;这个新创建的列表然后是 sorted 和 returned )
>>> a = 1
>>> dir(a) is dir(a)
False
第三,True
是bool
类型的一个实例,它是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/