[Tutor] new book available

Erik Price erikprice at mac.com
Tue Sep 9 09:12:56 EDT 2003


On Monday, September 8, 2003, at 03:03  PM, Alan Colburn wrote:

> One of the things that caught my attention was the
> author's distinguishing "new" style class definitions
> from "old" style ones.
>
>>>> class Test:
>
> is an old style definition.
>
>>>> class Test (object):
>
> is the newer style. I don't think I've seen this point
> discussed on PythonTutor or elsewhere. [Have I missed
> something?]

It's been tossed around a couple of times (though I'm not sure how 
recently).

If you want to create a new-style class, you inherit from object, 
otherwise you don't (or you inherit from a superclass that doesn't 
inherit from object).

The differences between old-style and new-style classes are pretty 
far-reaching, but some of the nice things are that you can subclass the 
"primitive" (*) types like int.  This way you can extend or modify 
functionality of a "primitive" by subclassing, whereas before if you 
wanted to create your own special kind of "primitive" you'd have to 
create it afresh as a new class and create an implementation for every 
single one of the methods provided by that "primitive" (like __add__, 
__and__, __or__, etc).  Such a delegate would also perform more slowly 
than a true subclass of the "primitive".

( * I use "primitive" in quotes because my understanding is that Python 
doesn't have any true primitives, technically "int" and "float" are 
classes themselves, but I didn't know what else to call them.)

There are also some other new features of new-style classes such as 
"slots" and "properties" which are documented as being for advanced 
users, and meta-classes (which let you modify the factories that churn 
out your classes, which in turn churn out your instances -- because a 
class is also an instance/object itself, just happens to be a callable 
object).  For a good explanation of meta-classes, I would refer to Alex 
Martelli's "Python in a Nutshell".



Erik




More information about the Tutor mailing list