Questions to the FAQ

Scott David Daniels Scott.Daniels at Acm.Org
Wed Jul 14 19:41:30 EDT 2004


Josef Wolf wrote:

> - FAQ entry 6.6:
> 
>   This FAQ entry makes a difference between new-style classes and classic
>   classes. An example is given for the new style and a hint is given how a
>   classic class would look like. But I can't see any difference in them:
>   The new-style example starts with "class Derived(Base):" and the hint for
>   the classic class is "class Derived(Base): ..." So what's the difference?
> 
> What am I missing here?

OK, I don't know where this comes in the FAQs (if it is there at all).
First, the shorter answer:

You can't have a new-style class inherit from a classic class, nor can
you have a new-style inherit from a classic class.  So, the "style" of
a class (classic or new-style) that inherits from some other class is
inherited.

Here is a useful lie (lie in that there are tricky ways to avoid this):
All new-style classes eventually inherit from the builtin class
"object", none of the old-style classes are subclasses of object.

So, for your question, after "class Derived(Base): ..."
if issubclass(Base, object): Derived is new-style.
if not issubclass(Base, object): Derived is classic.

or (perhaps interesting, perhaps more to the point, perhaps confusing):
if isinstance(Base, type): Derived is new-style.
if not isinstance(Base, type): Derived is classic.

Now a longer blather:

The difference between "classic classes" (or old-style classes as we
will eventually call them) is which "metaclass" they are built with.
Don't worry too much about that, you shouldn't fiddle with (or worry
about understanding) metaclasses until you know quite a lot about
Python's implementation.  The nickel explanation is that a metaclass
controls how a class works in the same way that a class controls how
an instance works.  The class controls how the instance behaves, and
the metaclass controls how that class does that controlling.  "type"
is a class for types, which is how the second pair of tests above work.
object is the simplest class of type "type" -- everything below it
is a new-style class.

There are ways other than inheriting eventually from object to set
up a metaclass to use for a class, but you should regard that as black
magic for a while -- a metaclass gives you enough rope to shoot
yourself in the foot.

-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list