我最近看到了这段代码:
x = [2, 3, 4]
if type(x) is list:
#some logic
并且很困惑 if
条件是如何关闭的...我认为 is
检查内存标识和 id
的 >x
与 list
的 id
不同,但如果是这样的话,这个 if
条件是如何发生的呢? (我的印象是 Python 中唯一的原生单例是 None
)。
最佳答案
这里x
是类 list
的一个实例,在新风格的类(class)中type()
返回实例本身的类,即 list
在这种情况下。考虑这个简单的例子:
>>> class A(object):
pass
...
>>> type(A()) #calling type on the instance returns its class
<class '__main__.A'>
>>> type(A()) is A
True
请注意,上面的示例不适用于用户定义的旧式类,因为所有实例的类型均为 instance
.
>>> class A:
pass
...
>>> type(A())
<type 'instance'>
关于python - 对身份感到困惑并且是运算符(operator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21633789/