Gre7g Luterman wrote:
> 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.

Python has two class systems: classic classes and new-style classes. 
New-style classes were introduced with Python 2.2. Classic classes 
remain for backwards compatibility. See section 3.3 "New-style and 
classic classes" in the Python 2.5 "Python Reference Manual" for an 
introduction.

PyInstance_Check() returns true only if an object is a classic class 
instance. Built-in types like list and dict are new-style classes, so 
PyInstance_Check() will return false (0) for list and dictionary 
instances. It will also return false for instances of Python classes 
inheriting from a new-style class.

> 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?!?
> 

Class "a" is a classic class. It does not inherit from a new-style 
class. In Python 2.5 Exception became a new-style class as well. dict is 
also a new-style class, as mentioned above.

> 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"?
> 

It all depends on what is meant by "instance-like". All Python classes 
are instances as well. In Python a class is defined by how it behaves 
rather than by some special interpreter level flag. So there is no 
definitive way to separate objects into "classes" and "instances". The 
best I can suggest is testing if an object is a "class-like" classic or 
new-style class. The inspect module defines an isclass function as follows:

def isclass(object):
     """Return true if the object is a class.

     Class objects provide these attributes:
         __doc__         documentation string
         __module__      name of module in which this class
                         was defined"""
     return isinstance(object, types.ClassType) or \
            hasattr(object, '__bases__')



---
Lenard Lindstrom
<[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to