[Tutor] New-style classes

Gonçalo Rodrigues op73418 at mail.telepac.pt
Sun Nov 2 14:09:45 EST 2003


On Sat, 1 Nov 2003 11:12:48 -0800 (PST), you wrote:

>I have heard about new-style classes, and I'm afraid
>I'm using old-style classes (since I'm learning from a
>book made for 2.0). Could somebody please explain what
>new-style classes are and their benefit over old-style
>classes?

For most of the programming problems there is no difference in using
either old-style or new-style classes.

Lloyd Kvam has already posted some references. Let me add a few things
-- this is all advanced stuff so I'll be short and cryptic :-)

- There are some notable differences, between old-style and new-style
classes. One has to do with special __*__ name lookup. Consider the
following example:

>>> #An old style class
>>> class Test:
... 	pass
... 
>>> a = Test()
>>> def it(self):
... 	yield None
... 	
>>> import types
>>> print types.MethodType.__doc__
instancemethod(function, instance, class)

Create an instance method object.

>>> #Sticking an __iter__ iterator method on the *instance* itself.
>>> a.__iter__ = types.MethodType(it, a, a.__class__)
>>> iter(a)
<generator object at 0x01120BC0>
>>> for elem in a:
... 	print elem
... 	
None
>>> #A new-style class
>>> class TestNew(object):
... 	pass
... 
>>> b = TestNew()
>>> #Sticking an __iter__ iterator method on the *instance* itself.
>>> b.__iter__ = types.MethodType(it, b, b.__class__)
>>> iter(b)
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: iteration over non-sequence
>>> 

I'll leave you to ponder on what's happening here.

- One other difference has to do with how Python linearizes the graph
of super classes of a given class. For new-style classes the C3 order
is used (from 2.3 onward) - there is an article somewhere in the net
by S. Pedroni I believe explaining this. But only with some contrived
inheritance graphs you'd notice the difference :-)

- There are some distinct advantages in using new-style classes.
Besides being able to subclass (almost all) builtin types you can use
features like super, properties and metaclasses. All advanced stuff,
as I said.

With my best regards,
G. Rodrigues



More information about the Tutor mailing list