New style classes

Tim Peters tim.one at comcast.net
Sun Mar 2 03:42:03 CET 2003


[Travis Oliphant]
> Forgive me if this question is naive.

Oh, all right <wink>.  I doubt that it is, though.

> I am trying to understand new-style classes.  In particular I want to be
> able to detect them in C-code.

Precision in language will be key to solving your problem.  Let's start
here:  do you really want to detect new-style classes, or instances of
new-style classes?  Do you realize that a new-style class is itself an
instance of a new-style class (the latter being the former's metaclass)?

> I understand that PyInstance_Check(obj) returns true in C if obj is an
> instance of an old-style class.

Right.

> However, it does not return true if obj is an instance of a new-style
> class.

Ditto.

> So, how does one check in C whether or not obj is an instance of a class
> (either old style or new style)?

If I were you, I'd try to reframe the problem so that this question
vanishes.  If you're determined, PyObject_HasAttrString(obj, "__class__")
may get close enough, but, as above, new-style classes are themselves
instances of other new-style classes, so the distinction between "class" and
"instance" has become pretty empty.

>>> class C(object):
...     pass
...
>>> C().__class__
<class '__main__.C'>
>>> C.__class__
<type 'type'>
>>> C.__class__.__class__
<type 'type'>
>>> int.__class__
<type 'type'>
>>> class C:
...     pass
...
>>> C().__class__
<class __main__.C at 0x006A4930>
>>> C.__class__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: class C has no attribute '__class__'
>>>

IOW, everything there had a __class__ attribute except for an old-style
class.






More information about the Python-list mailing list