Detecting a new style class

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Apr 23 05:55:14 EDT 2002


Graham Ashton <gashton at cmedltd.com> wrote in 
news:mailman.1019552082.8541.python-list at python.org:

> This means that I'd like to be able to detect whether my class is being
> subclassed by a new or classic class. To do that I'm testing self to see
> if it has a __new__ attribute. Is there a better way to do it?

You could test that type(self)==types.InstanceType

A better way to do it would be to write the code so that it works for both 
or only for new style classes (since if you make your base class newstyle 
then all subclasses are automatically newstyle).

> 
> I find that the behaviour varies depending on the order in which a
> class's super classes are defined. In the example below, I'd like the
> instantiation of class B to throw the same RuntimeError as A:
> 
> Python 2.2 (#2, Mar 11 2002, 13:24:00) 
> [GCC 2.95.3 20010315 (release)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> from AbstractSingleton import AbstractSingleton
>>>> class A(AbstractSingleton, object):
> ...   pass
> ... 
>>>> a = A()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "AbstractSingleton.py", line 60, in __init__
>     self.__check_for_new_style_class()
>   File "AbstractSingleton.py", line 66, in __check_for_new_style_class
>     raise RuntimeError, "New style classes are not supported"
> RuntimeError: New style classes are not supported
>>>> class B(object, AbstractSingleton):
> ...   pass
> ... 
>>>> b = B()
>>>> 
> 
Perhaps if B was to call AbstractSingleton.__init__ this would do what you 
want, but since only object.__init__ is called here, your checks are never 
done.

You need to make B explicitly call AbstractSingleton here or make 
AbstractSingleton a new style class in which case its __init__ will be 
called.


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list