Easy Q: dealing with object type

Steven Bethard steven.bethard at gmail.com
Thu Feb 3 12:47:10 EST 2005


Just wrote:
> In article <SJmdnddykYoAOpzfRVn-hA at comcast.com>,
>  Steven Bethard <steven.bethard at gmail.com> wrote:
>>
>>py> class A:
>>...     pass
>>...
>>py> class B:
>>...     pass
>>...
>>py> a = A()
>>py> a.__class__ == A
>>True
>>py> a.__class__ == B
>>False
> 
> Uh, isinstance(a, A) works for both new-style and old-style classes. 
> Heck, isinstance() even works in Python 1.5.2...

The OP asked "Given some object ... how do you test its type?".  I 
interpreted this as a strict check, not a transitive check:

py> class A:
...     pass
...
py> class B(A):
...     pass
...
py> b = B()
py> isinstance(b, B)
True
py> isinstance(b, A)
True
py> b.__class__ == B
True
py> b.__class__ == A
False

Of course, if the OP doesn't need the strict check here, isinstance is, 
of course, the right answer.

STeve



More information about the Python-list mailing list