2024-05-14 13:46:50 发布
网友
我最近看到了以下代码:
x = [2, 3, 4] if type(x) is list: #some logic
我很困惑if条件是如何发生的……我认为is检查内存身份,x的id与list的id是不同的,但如果是这样的话,这个if条件是如何发生的呢(我的印象是Python中唯一的原生单例是None)
if
is
x
id
list
None
这里x是类list的实例,在新样式类中type()返回实例本身的类,即在本例中list。考虑这个简单的例子:
type()
>>> class A(object): pass ... >>> type(A()) #calling type on the instance returns its class <class '__main__.A'> >>> type(A()) is A True
请注意,上面的示例不适用于用户定义的旧式类,因为其中的所有实例都属于instance类型
instance
>>> class A: pass ... >>> type(A()) <type 'instance'>
这里
x
是类list
的实例,在新样式类中type()
返回实例本身的类,即在本例中list
。考虑这个简单的例子:请注意,上面的示例不适用于用户定义的旧式类,因为其中的所有实例都属于
instance
类型相关问题 更多 >
编程相关推荐