source: trunk/essentials/dev-lang/python/Demo/metaclasses/index.html@ 3437

Last change on this file since 3437 was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 20.1 KB
Line 
1<HTML>
2
3<HEAD>
4<TITLE>Metaclasses in Python 1.5</TITLE>
5</HEAD>
6
7<BODY BGCOLOR="FFFFFF">
8
9<H1>Metaclasses in Python 1.5</H1>
10<H2>(A.k.a. The Killer Joke :-)</H2>
11
12<HR>
13
14(<i>Postscript:</i> reading this essay is probably not the best way to
15understand the metaclass hook described here. See a <A
16HREF="meta-vladimir.txt">message posted by Vladimir Marangozov</A>
17which may give a gentler introduction to the matter. You may also
18want to search Deja News for messages with "metaclass" in the subject
19posted to comp.lang.python in July and August 1998.)
20
21<HR>
22
23<P>In previous Python releases (and still in 1.5), there is something
24called the ``Don Beaudry hook'', after its inventor and champion.
25This allows C extensions to provide alternate class behavior, thereby
26allowing the Python class syntax to be used to define other class-like
27entities. Don Beaudry has used this in his infamous <A
28HREF="http://maigret.cog.brown.edu/pyutil/">MESS</A> package; Jim
29Fulton has used it in his <A
30HREF="http://www.digicool.com/releases/ExtensionClass/">Extension
31Classes</A> package. (It has also been referred to as the ``Don
32Beaudry <i>hack</i>,'' but that's a misnomer. There's nothing hackish
33about it -- in fact, it is rather elegant and deep, even though
34there's something dark to it.)
35
36<P>(On first reading, you may want to skip directly to the examples in
37the section "Writing Metaclasses in Python" below, unless you want
38your head to explode.)
39
40<P>
41
42<HR>
43
44<P>Documentation of the Don Beaudry hook has purposefully been kept
45minimal, since it is a feature of incredible power, and is easily
46abused. Basically, it checks whether the <b>type of the base
47class</b> is callable, and if so, it is called to create the new
48class.
49
50<P>Note the two indirection levels. Take a simple example:
51
52<PRE>
53class B:
54 pass
55
56class C(B):
57 pass
58</PRE>
59
60Take a look at the second class definition, and try to fathom ``the
61type of the base class is callable.''
62
63<P>(Types are not classes, by the way. See questions 4.2, 4.19 and in
64particular 6.22 in the <A
65HREF="http://www.python.org/cgi-bin/faqw.py" >Python FAQ</A>
66for more on this topic.)
67
68<P>