"isinstance" question
Thomas Jollans
thomas at jollans.com
Wed Jun 23 05:50:47 EDT 2010
On 06/23/2010 08:39 AM, Satish Eerpini wrote:
>
>
> I want to test whether an object is an instance of any
> user-defined
> class. "isinstance" is less helpful than one would expect.
>
> >>> import types
> >>> class foo() : # define dummy class
> ... pass
> ...
> >>> x = foo()
> >>>
> >>> type(x)
> <type 'instance'>
> >>>
> >>> isinstance(x, types.ClassType)
> False
> >>> isinstance(x, types.InstanceType)
> True
> >>> foo
> <class __main__.foo at 0x004A2BD0>
> >>> x
> <__main__.foo instance at 0x020080A8>
>
> So far, so good. x is an InstanceType. But let's try a
> class with a constructor:
>
> >>> class bar(object) :
> ... def __init__(self, val) :
> ... self.val = val
> ...
> >>> b = bar(100)
> >>> b
> <__main__.bar object at 0x01FF50D0>
> >>> isinstance(b, types.InstanceType)
> False
> >>> isinstance(b, types.ClassType)
> False
> >>>>>> bar
> <class '__main__.bar'>
>
> well the same code on my side returns true when you run isinstance(b,
> types.InstanceType) even when the class has a constructor. Why is there
> a difference in the output when we are both using Cython 2.6 ?? (2.6.4
> to be exact)
I assume you mean CPython, not Cython.
As Gabriel said, the difference is that bar is a subclass of object. If
isinstance(bar(100), types.InstanceType), then you did not subclass
object, and get an old-style class.
More information about the Python-list
mailing list