문제

I recently saw this code:

x = [2, 3, 4]
if type(x) is list:
    #some logic

and was confused how the if condition went off...I thought that is checks for memory identity and the id of x is different from the id of list, but if that's the case how did this if condition even go off? (I was under the impression that the only native singleton in Python was None).

도움이 되었습니까?

해결책

Here x is an instance of class list, in new style classes type() returns the class of the instance itself, i.e list in this case. Consider this simple example:

>>> class A(object):
    pass
... 
>>> type(A())         #calling type on the instance returns its class
<class '__main__.A'>
>>> type(A()) is A
True

Note that the above example will not work for user defined old-style classes as all the instances there were of type instance.

>>> class A:
    pass
... 
>>> type(A())
<type 'instance'>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top