Creating Classes

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Dec 21 02:53:51 EST 2009


On Sun, 20 Dec 2009 11:11:54 -0500, Steve Holden wrote:

> Dave Angel wrote:
> [...]
>> We were talking about 2.x   And I explicitly mentioned 3.x because if
>> one develops code that depends on old-style classes, they'll be in
>> trouble with 3.x, which has no way to specify old-style classes.  In
>> 3.x, all classes are new-style.  And although it'll no longer matter
>> whether you specify (object), it doesn't do any harm.  As I said, it's
>> a good habit for a beginner to get into when defining classes.
>> 
> I maintain that this almost-cargo-cult belief over-complicates things
> for language beginners. How long do you have to be using Python before
> you make your first super() call? 

That depends on who you are and what you're doing.

Are you a n00b who has never programmed before?

An old Fortran or Pascal dinosaur who doesn't like that new fangled 
object stuff?

A former Java OO guru whose class hierarchies are 85 classes deep on 
average?

Someone who just discovered multiple inheritance and now everything looks 
like a nail?



> How many programs behave differently
> with old-style vs. new-style classes?

Any program that uses properties will behave differently.

__getattribute__ and __slots__ will not work at all in old-style classes.

There will be subtle differences, e.g. isinstance(type, MyClass) will 
return False if MyClass is old-style. The default repr and str of 
instances will look different (which may or may not count as different 
behaviour). Speed and efficiency will be different.

So I guess the correct answer to your question is "All of them". The 
interesting question is, what's the magnitude of the differences?

The advice I used to give was, unless you care about the difference, 
always inherit from object because new-style classes are the way of the 
future. Unfortunately, it is no longer obvious whether something in 
isolation is a new-style or old-style class, as you have to know the 
target Python version.




-- 
Steven



More information about the Python-list mailing list