What is an instance and what isn't?

Terry Reedy tjreedy at udel.edu
Thu May 24 15:59:17 EDT 2007


"Gre7g Luterman" <hafeliel at yahoo.com> wrote in message 
news:HKedneXu0YpQMcjbnZ2dnUVZ_jCdnZ2d at bresnan.com...
|I suppose I was lulled into complacency by how Python makes so many things
| look like classes, but I'm starting to realize that they're not, are 
they?
|
| I'm writing a C program which handles Python objects in different ways 
based
| on their type. I do a PyInstance_Check(PyObj) to determine if the PyObj 
is
| an instance, but it is returning 0 on a lot of stuff that I thought would 
be
| an instance. So I did the following simple test on three things that look
| like instances:
|
| Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
(Intel)]
| on win32
| Type "help", "copyright", "credits" or "license" for more information.
| >>> class a: pass
| ...
| >>> type(a())
| <type 'instance'>
| >>> type(Exception())
| <type 'exceptions.Exception'>
| >>> class b(dict): pass
| ...
| >>> type(b())
| <class '__main__.b'>
|
| I was relieved that a() returns an instance, but I was surprised that
| Exceptions aren't really instances at all. And what's the deal with 
derving
| a class from a standard type like a dictionary? I thought for sure, that
| would be an instance, but this shows it is a class?!?
|
| Can anyone explain the last one and/or give me a simple test I can do in 
C
| to determine whether a Python object is "instance-like"?

Your problem is mixing two different meanings of 'instance', one obsolete. 
Everything is an instance of its type/class.  However, for old-style 
classes, all instances of user defined classes are instances of type 
'instance' instead of their class.  This is usually not very helpful.  New 
style classes fix this.

>>> class a(object): pass

>>> type(a())
<class '__main__.a'>

In 2.5, Exception changed from old-style to new.

Terry Jan Reedy








More information about the Python-list mailing list