"isinstance" question
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Jun 23 01:06:07 EDT 2010
En Tue, 22 Jun 2010 23:45:07 -0300, John Nagle <nagle at animats.com>
escribió:
> 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'>
>
> Without a constructor, we get an "instance". With a constructor,
> we get an "object", one which is not an InstanceType.
That's not the relevant difference. In the first case, you don't inherit
from object; in the second one, you do.
foo is a "classic" class (or "old-style" class); x is an instance of foo,
its *type* is InstanceType, its *class* is foo. All instances of any other
classic class have the same type (InstanceType).
bar is a "new-style" class, b is an instance of bar, its type is bar, its
class is bar. class and type are equivalent for new style classes; things
are a lot more regular and predictable. In Python 3.x classic classes are
gone.
--
Gabriel Genellina
More information about the Python-list
mailing list