Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / src / nas,5.n2.os.2 / lib / python / html / python / tut / node11.html
CommitLineData
86530b38
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<html>
3<head>
4<link rel="STYLESHEET" href="tut.css" type='text/css' />
5<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
6<link rel='start' href='../index.html' title='Python Documentation Index' />
7<link rel="first" href="tut.html" title='Python Tutorial' />
8<link rel='contents' href='node2.html' title="Contents" />
9<link rel='index' href='node19.html' title='Index' />
10<link rel='last' href='about.html' title='About this document...' />
11<link rel='help' href='about.html' title='About this document...' />
12<link rel="next" href="node12.html" />
13<link rel="prev" href="node10.html" />
14<link rel="parent" href="tut.html" />
15<link rel="next" href="node12.html" />
16<meta name='aesop' content='information' />
17<title>9. Classes </title>
18</head>
19<body>
20<DIV CLASS="navigation">
21<div id='top-navigation-panel' xml:id='top-navigation-panel'>
22<table align="center" width="100%" cellpadding="0" cellspacing="2">
23<tr>
24<td class='online-navigation'><a rel="prev" title="8. Errors and Exceptions"
25 href="node10.html"><img src='../icons/previous.png'
26 border='0' height='32' alt='Previous Page' width='32' /></A></td>
27<td class='online-navigation'><a rel="parent" title="Python Tutorial"
28 href="tut.html"><img src='../icons/up.png'
29 border='0' height='32' alt='Up One Level' width='32' /></A></td>
30<td class='online-navigation'><a rel="next" title="10. Brief Tour of"
31 href="node12.html"><img src='../icons/next.png'
32 border='0' height='32' alt='Next Page' width='32' /></A></td>
33<td align="center" width="100%">Python Tutorial</td>
34<td class='online-navigation'><a rel="contents" title="Table of Contents"
35 href="node2.html"><img src='../icons/contents.png'
36 border='0' height='32' alt='Contents' width='32' /></A></td>
37<td class='online-navigation'><img src='../icons/blank.png'
38 border='0' height='32' alt='' width='32' /></td>
39<td class='online-navigation'><a rel="index" title="Index"
40 href="node19.html"><img src='../icons/index.png'
41 border='0' height='32' alt='Index' width='32' /></A></td>
42</tr></table>
43<div class='online-navigation'>
44<b class="navlabel">Previous:</b>
45<a class="sectref" rel="prev" href="node10.html">8. Errors and Exceptions</A>
46<b class="navlabel">Up:</b>
47<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
48<b class="navlabel">Next:</b>
49<a class="sectref" rel="next" href="node12.html">10. Brief Tour of</A>
50</div>
51<hr /></div>
52</DIV>
53<!--End of Navigation Panel-->
54<div class='online-navigation'>
55<!--Table of Child-Links-->
56<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
57
58<UL CLASS="ChildLinks">
59<LI><A href="node11.html#SECTION0011100000000000000000">9.1 A Word About Terminology</a>
60<LI><A href="node11.html#SECTION0011200000000000000000">9.2 Python Scopes and Name Spaces</a>
61<LI><A href="node11.html#SECTION0011300000000000000000">9.3 A First Look at Classes</a>
62<UL>
63<LI><A href="node11.html#SECTION0011310000000000000000">9.3.1 Class Definition Syntax</a>
64<LI><A href="node11.html#SECTION0011320000000000000000">9.3.2 Class Objects</a>
65<LI><A href="node11.html#SECTION0011330000000000000000">9.3.3 Instance Objects</a>
66<LI><A href="node11.html#SECTION0011340000000000000000">9.3.4 Method Objects</a>
67</ul>
68<LI><A href="node11.html#SECTION0011400000000000000000">9.4 Random Remarks</a>
69<LI><A href="node11.html#SECTION0011500000000000000000">9.5 Inheritance</a>
70<UL>
71<LI><A href="node11.html#SECTION0011510000000000000000">9.5.1 Multiple Inheritance</a>
72</ul>
73<LI><A href="node11.html#SECTION0011600000000000000000">9.6 Private Variables</a>
74<LI><A href="node11.html#SECTION0011700000000000000000">9.7 Odds and Ends</a>
75<LI><A href="node11.html#SECTION0011800000000000000000">9.8 Exceptions Are Classes Too</a>
76<LI><A href="node11.html#SECTION0011900000000000000000">9.9 Iterators</a>
77<LI><A href="node11.html#SECTION00111000000000000000000">9.10 Generators</a>
78<LI><A href="node11.html#SECTION00111100000000000000000">9.11 Generator Expressions</a>
79</ul>
80<!--End of Table of Child-Links-->
81</div>
82<HR>
83
84<H1><A NAME="SECTION0011000000000000000000"></A><A NAME="classes"></A>
85<BR>
869. Classes
87</H1>
88
89<P>
90Python's class mechanism adds classes to the language with a minimum
91of new syntax and semantics. It is a mixture of the class mechanisms
92found in C++ and Modula-3. As is true for modules, classes in Python
93do not put an absolute barrier between definition and user, but rather
94rely on the politeness of the user not to ``break into the
95definition.'' The most important features of classes are retained
96with full power, however: the class inheritance mechanism allows
97multiple base classes, a derived class can override any methods of its
98base class or classes, and a method can call the method of a base class with the
99same name. Objects can contain an arbitrary amount of private data.
100
101<P>
102In C++ terminology, all class members (including the data members) are
103<em>public</em>, and all member functions are <em>virtual</em>. There are
104no special constructors or destructors. As in Modula-3, there are no
105shorthands for referencing the object's members from its methods: the
106method function is declared with an explicit first argument
107representing the object, which is provided implicitly by the call. As
108in Smalltalk, classes themselves are objects, albeit in the wider
109sense of the word: in Python, all data types are objects. This
110provides semantics for importing and renaming. Unlike
111C++ and Modula-3, built-in types can be used as base classes for
112extension by the user. Also, like in C++ but unlike in Modula-3, most
113built-in operators with special syntax (arithmetic operators,
114subscripting etc.) can be redefined for class instances.
115
116<P>
117
118<H1><A NAME="SECTION0011100000000000000000"></A><A NAME="terminology"></A>
119<BR>
1209.1 A Word About Terminology
121</H1>
122
123<P>
124Lacking universally accepted terminology to talk about classes, I will
125make occasional use of Smalltalk and C++ terms. (I would use Modula-3
126terms, since its object-oriented semantics are closer to those of
127Python than C++, but I expect that few readers have heard of it.)
128
129<P>
130Objects have individuality, and multiple names (in multiple scopes)
131can be bound to the same object. This is known as aliasing in other
132languages. This is usually not appreciated on a first glance at
133Python, and can be safely ignored when dealing with immutable basic
134types (numbers, strings, tuples). However, aliasing has an
135(intended!) effect on the semantics of Python code involving mutable
136objects such as lists, dictionaries, and most types representing
137entities outside the program (files, windows, etc.). This is usually
138used to the benefit of the program, since aliases behave like pointers
139in some respects. For example, passing an object is cheap since only
140a pointer is passed by the implementation; and if a function modifies
141an object passed as an argument, the caller will see the change -- this
142eliminates the need for two different argument passing mechanisms as in
143Pascal.
144
145<P>
146
147<H1><A NAME="SECTION0011200000000000000000"></A><A NAME="scopes"></A>
148<BR>
1499.2 Python Scopes and Name Spaces
150</H1>
151
152<P>
153Before introducing classes, I first have to tell you something about
154Python's scope rules. Class definitions play some neat tricks with
155namespaces, and you need to know how scopes and namespaces work to
156fully understand what's going on. Incidentally, knowledge about this
157subject is useful for any advanced Python programmer.
158
159<P>
160Let's begin with some definitions.
161
162<P>
163A <em>namespace</em> is a mapping from names to objects. Most
164namespaces are currently implemented as Python dictionaries, but
165that's normally not noticeable in any way (except for performance),
166and it may change in the future. Examples of namespaces are: the set
167of built-in names (functions such as <tt class="function">abs()</tt>, and built-in
168exception names); the global names in a module; and the local names in
169a function invocation. In a sense the set of attributes of an object
170also form a namespace. The important thing to know about namespaces
171is that there is absolutely no relation between names in different
172namespaces; for instance, two different modules may both define a
173function ``maximize'' without confusion -- users of the modules must
174prefix it with the module name.
175
176<P>
177By the way, I use the word <em>attribute</em> for any name following a
178dot -- for example, in the expression <code>z.real</code>, <code>real</code> is
179an attribute of the object <code>z</code>. Strictly speaking, references to
180names in modules are attribute references: in the expression
181<code>modname.funcname</code>, <code>modname</code> is a module object and
182<code>funcname</code> is an attribute of it. In this case there happens to
183be a straightforward mapping between the module's attributes and the
184global names defined in the module: they share the same namespace!
185<A NAME="tex2html5"
186 HREF="#foot1849"><SUP>9.1</SUP></A>
187<P>
188Attributes may be read-only or writable. In the latter case,
189assignment to attributes is possible. Module attributes are writable:
190you can write "<tt class="samp">modname.the_answer = 42</tt>". Writable attributes may
191also be deleted with the <tt class="keyword">del</tt> statement. For example,
192"<tt class="samp">del modname.the_answer</tt>" will remove the attribute
193<tt class="member">the_answer</tt> from the object named by <code>modname</code>.
194
195<P>
196Name spaces are created at different moments and have different
197lifetimes. The namespace containing the built-in names is created
198when the Python interpreter starts up, and is never deleted. The
199global namespace for a module is created when the module definition
200is read in; normally, module namespaces also last until the
201interpreter quits. The statements executed by the top-level
202invocation of the interpreter, either read from a script file or
203interactively, are considered part of a module called
204<tt class="module">__main__</tt>, so they have their own global namespace. (The
205built-in names actually also live in a module; this is called
206<tt class="module">__builtin__</tt>.)
207
208<P>
209The local namespace for a function is created when the function is
210called, and deleted when the function returns or raises an exception
211that is not handled within the function. (Actually, forgetting would
212be a better way to describe what actually happens.) Of course,
213recursive invocations each have their own local namespace.
214
215<P>
216A <em>scope</em> is a textual region of a Python program where a
217namespace is directly accessible. ``Directly accessible'' here means
218that an unqualified reference to a name attempts to find the name in
219the namespace.
220
221<P>
222Although scopes are determined statically, they are used dynamically.
223At any time during execution, there are at least three nested scopes whose
224namespaces are directly accessible: the innermost scope, which is searched
225first, contains the local names; the namespaces of any enclosing
226functions, which are searched starting with the nearest enclosing scope;
227the middle scope, searched next, contains the current module's global names;
228and the outermost scope (searched last) is the namespace containing built-in
229names.
230
231<P>
232If a name is declared global, then all references and assignments go
233directly to the middle scope containing the module's global names.
234Otherwise, all variables found outside of the innermost scope are read-only
235(an attempt to write to such a variable will simply create a <em>new</em>
236local variable in the innermost scope, leaving the identically named
237outer variable unchanged).
238
239<P>
240Usually, the local scope references the local names of the (textually)
241current function. Outside functions, the local scope references
242the same namespace as the global scope: the module's namespace.
243Class definitions place yet another namespace in the local scope.
244
245<P>
246It is important to realize that scopes are determined textually: the
247global scope of a function defined in a module is that module's
248namespace, no matter from where or by what alias the function is
249called. On the other hand, the actual search for names is done
250dynamically, at run time -- however, the language definition is
251evolving towards static name resolution, at ``compile'' time, so don't
252rely on dynamic name resolution! (In fact, local variables are
253already determined statically.)
254
255<P>
256A special quirk of Python is that assignments always go into the
257innermost scope. Assignments do not copy data -- they just
258bind names to objects. The same is true for deletions: the statement
259"<tt class="samp">del x</tt>" removes the binding of <code>x</code> from the namespace
260referenced by the local scope. In fact, all operations that introduce
261new names use the local scope: in particular, import statements and
262function definitions bind the module or function name in the local
263scope. (The <tt class="keyword">global</tt> statement can be used to indicate that
264particular variables live in the global scope.)
265
266<P>
267
268<H1><A NAME="SECTION0011300000000000000000"></A><A NAME="firstClasses"></A>
269<BR>
2709.3 A First Look at Classes
271</H1>
272
273<P>
274Classes introduce a little bit of new syntax, three new object types,
275and some new semantics.
276
277<P>
278
279<H2><A NAME="SECTION0011310000000000000000"></A><A NAME="classDefinition"></A>
280<BR>
2819.3.1 Class Definition Syntax
282</H2>
283
284<P>
285The simplest form of class definition looks like this:
286
287<P>
288<div class="verbatim"><pre>
289class ClassName:
290 &lt;statement-1&gt;
291 .
292 .
293 .
294 &lt;statement-N&gt;
295</pre></div>
296
297<P>
298Class definitions, like function definitions
299(<tt class="keyword">def</tt> statements) must be executed before they have any
300effect. (You could conceivably place a class definition in a branch
301of an <tt class="keyword">if</tt> statement, or inside a function.)
302
303<P>
304In practice, the statements inside a class definition will usually be
305function definitions, but other statements are allowed, and sometimes
306useful -- we'll come back to this later. The function definitions
307inside a class normally have a peculiar form of argument list,
308dictated by the calling conventions for methods -- again, this is
309explained later.
310
311<P>
312When a class definition is entered, a new namespace is created, and
313used as the local scope -- thus, all assignments to local variables
314go into this new namespace. In particular, function definitions bind
315the name of the new function here.
316
317<P>
318When a class definition is left normally (via the end), a <em>class
319object</em> is created. This is basically a wrapper around the contents
320of the namespace created by the class definition; we'll learn more
321about class objects in the next section. The original local scope
322(the one in effect just before the class definition was entered) is
323reinstated, and the class object is bound here to the class name given
324in the class definition header (<tt class="class">ClassName</tt> in the example).
325
326<P>
327
328<H2><A NAME="SECTION0011320000000000000000"></A><A NAME="classObjects"></A>
329<BR>
3309.3.2 Class Objects
331</H2>
332
333<P>
334Class objects support two kinds of operations: attribute references
335and instantiation.
336
337<P>
338<em>Attribute references</em> use the standard syntax used for all
339attribute references in Python: <code>obj.name</code>. Valid attribute
340names are all the names that were in the class's namespace when the
341class object was created. So, if the class definition looked like
342this:
343
344<P>
345<div class="verbatim"><pre>
346class MyClass:
347 "A simple example class"
348 i = 12345
349 def f(self):
350 return 'hello world'
351</pre></div>
352
353<P>
354then <code>MyClass.i</code> and <code>MyClass.f</code> are valid attribute
355references, returning an integer and a function object, respectively.
356Class attributes can also be assigned to, so you can change the value
357of <code>MyClass.i</code> by assignment. <tt class="member">__doc__</tt> is also a valid
358attribute, returning the docstring belonging to the class: <code>"A
359simple example class"</code>.
360
361<P>
362Class <em>instantiation</em> uses function notation. Just pretend that
363the class object is a parameterless function that returns a new
364instance of the class. For example (assuming the above class):
365
366<P>
367<div class="verbatim"><pre>
368x = MyClass()
369</pre></div>
370
371<P>
372creates a new <em>instance</em> of the class and assigns this object to
373the local variable <code>x</code>.
374
375<P>
376The instantiation operation (``calling'' a class object) creates an
377empty object. Many classes like to create objects with instances
378customized to a specific initial state.
379Therefore a class may define a special method named
380<tt class="method">__init__()</tt>, like this:
381
382<P>
383<div class="verbatim"><pre>
384 def __init__(self):
385 self.data = []
386</pre></div>
387
388<P>
389When a class defines an <tt class="method">__init__()</tt> method, class
390instantiation automatically invokes <tt class="method">__init__()</tt> for the
391newly-created class instance. So in this example, a new, initialized
392instance can be obtained by:
393
394<P>
395<div class="verbatim"><pre>
396x = MyClass()
397</pre></div>
398
399<P>
400Of course, the <tt class="method">__init__()</tt> method may have arguments for
401greater flexibility. In that case, arguments given to the class
402instantiation operator are passed on to <tt class="method">__init__()</tt>. For
403example,
404
405<P>
406<div class="verbatim"><pre>
407&gt;&gt;&gt; class Complex:
408... def __init__(self, realpart, imagpart):
409... self.r = realpart
410... self.i = imagpart
411...
412&gt;&gt;&gt; x = Complex(3.0, -4.5)
413&gt;&gt;&gt; x.r, x.i
414(3.0, -4.5)
415</pre></div>
416
417<P>
418
419<H2><A NAME="SECTION0011330000000000000000"></A><A NAME="instanceObjects"></A>
420<BR>
4219.3.3 Instance Objects
422</H2>
423
424<P>
425Now what can we do with instance objects? The only operations
426understood by instance objects are attribute references. There are
427two kinds of valid attribute names, data attributes and methods.
428
429<P>
430<em>data attributes</em> correspond to
431``instance variables'' in Smalltalk, and to ``data members'' in
432C++. Data attributes need not be declared; like local variables,
433they spring into existence when they are first assigned to. For
434example, if <code>x</code> is the instance of <tt class="class">MyClass</tt> created above,
435the following piece of code will print the value <code>16</code>, without
436leaving a trace:
437
438<P>
439<div class="verbatim"><pre>
440x.counter = 1
441while x.counter &lt; 10:
442 x.counter = x.counter * 2
443print x.counter
444del x.counter
445</pre></div>
446
447<P>
448The other kind of instance attribute reference is a <em>method</em>.
449A method is a function that ``belongs to'' an
450object. (In Python, the term method is not unique to class instances:
451other object types can have methods as well. For example, list objects have
452methods called append, insert, remove, sort, and so on. However,
453in the following discussion, we'll use the term method exclusively to mean
454methods of class instance objects, unless explicitly stated otherwise.)
455
456<P>
457Valid method names of an instance object depend on its class. By
458definition, all attributes of a class that are function
459objects define corresponding methods of its instances. So in our
460example, <code>x.f</code> is a valid method reference, since
461<code>MyClass.f</code> is a function, but <code>x.i</code> is not, since
462<code>MyClass.i</code> is not. But <code>x.f</code> is not the same thing as
463<code>MyClass.f</code> -- it is a <a id='l2h-33' xml:id='l2h-33'></a><em>method object</em>, not
464a function object.
465
466<P>
467
468<H2><A NAME="SECTION0011340000000000000000"></A><A NAME="methodObjects"></A>
469<BR>
4709.3.4 Method Objects
471</H2>
472
473<P>
474Usually, a method is called right after it is bound:
475
476<P>
477<div class="verbatim"><pre>
478x.f()
479</pre></div>
480
481<P>
482In the <tt class="class">MyClass</tt> example, this will return the string <code>'hello world'</code>.
483However, it is not necessary to call a method right away:
484<code>x.f</code> is a method object, and can be stored away and called at a
485later time. For example:
486
487<P>
488<div class="verbatim"><pre>
489xf = x.f
490while True:
491 print xf()
492</pre></div>
493
494<P>
495will continue to print "<tt class="samp">hello world</tt>" until the end of time.
496
497<P>
498What exactly happens when a method is called? You may have noticed
499that <code>x.f()</code> was called without an argument above, even though
500the function definition for <tt class="method">f</tt> specified an argument. What
501happened to the argument? Surely Python raises an exception when a
502function that requires an argument is called without any -- even if
503the argument isn't actually used...
504
505<P>
506Actually, you may have guessed the answer: the special thing about
507methods is that the object is passed as the first argument of the
508function. In our example, the call <code>x.f()</code> is exactly equivalent
509to <code>MyClass.f(x)</code>. In general, calling a method with a list of
510<var>n</var> arguments is equivalent to calling the corresponding function
511with an argument list that is created by inserting the method's object
512before the first argument.
513
514<P>
515If you still don't understand how methods work, a look at the
516implementation can perhaps clarify matters. When an instance
517attribute is referenced that isn't a data attribute, its class is
518searched. If the name denotes a valid class attribute that is a
519function object, a method object is created by packing (pointers to)
520the instance object and the function object just found together in an
521abstract object: this is the method object. When the method object is
522called with an argument list, it is unpacked again, a new argument
523list is constructed from the instance object and the original argument
524list, and the function object is called with this new argument list.
525
526<P>
527
528<H1><A NAME="SECTION0011400000000000000000"></A><A NAME="remarks"></A>
529<BR>
5309.4 Random Remarks
531</H1>
532
533<P>
534Data attributes override method attributes with the same name; to
535avoid accidental name conflicts, which may cause hard-to-find bugs in
536large programs, it is wise to use some kind of convention that
537minimizes the chance of conflicts. Possible conventions include
538capitalizing method names, prefixing data attribute names with a small
539unique string (perhaps just an underscore), or using verbs for methods
540and nouns for data attributes.
541
542<P>
543Data attributes may be referenced by methods as well as by ordinary
544users (``clients'') of an object. In other words, classes are not
545usable to implement pure abstract data types. In fact, nothing in
546Python makes it possible to enforce data hiding -- it is all based
547upon convention. (On the other hand, the Python implementation,
548written in C, can completely hide implementation details and control
549access to an object if necessary; this can be used by extensions to
550Python written in C.)
551
552<P>
553Clients should use data attributes with care -- clients may mess up
554invariants maintained by the methods by stamping on their data
555attributes. Note that clients may add data attributes of their own to
556an instance object without affecting the validity of the methods, as
557long as name conflicts are avoided -- again, a naming convention can
558save a lot of headaches here.
559
560<P>
561There is no shorthand for referencing data attributes (or other
562methods!) from within methods. I find that this actually increases
563the readability of methods: there is no chance of confusing local
564variables and instance variables when glancing through a method.
565
566<P>
567Often, the first argument of a method is called
568<code>self</code>. This is nothing more than a convention: the name
569<code>self</code> has absolutely no special meaning to Python. (Note,
570however, that by not following the convention your code may be less
571readable to other Python programmers, and it is also conceivable that
572a <em>class browser</em> program might be written that relies upon such a
573convention.)
574
575<P>
576Any function object that is a class attribute defines a method for
577instances of that class. It is not necessary that the function
578definition is textually enclosed in the class definition: assigning a
579function object to a local variable in the class is also ok. For
580example:
581
582<P>
583<div class="verbatim"><pre>
584# Function defined outside the class
585def f1(self, x, y):
586 return min(x, x+y)
587
588class C:
589 f = f1
590 def g(self):
591 return 'hello world'
592 h = g
593</pre></div>
594
595<P>
596Now <code>f</code>, <code>g</code> and <code>h</code> are all attributes of class
597<tt class="class">C</tt> that refer to function objects, and consequently they are all
598methods of instances of <tt class="class">C</tt> -- <code>h</code> being exactly equivalent
599to <code>g</code>. Note that this practice usually only serves to confuse
600the reader of a program.
601
602<P>
603Methods may call other methods by using method attributes of the
604<code>self</code> argument:
605
606<P>
607<div class="verbatim"><pre>
608class Bag:
609 def __init__(self):
610 self.data = []
611 def add(self, x):
612 self.data.append(x)
613 def addtwice(self, x):
614 self.add(x)
615 self.add(x)
616</pre></div>
617
618<P>
619Methods may reference global names in the same way as ordinary
620functions. The global scope associated with a method is the module
621containing the class definition. (The class itself is never used as a
622global scope!) While one rarely encounters a good reason for using
623global data in a method, there are many legitimate uses of the global
624scope: for one thing, functions and modules imported into the global
625scope can be used by methods, as well as functions and classes defined
626in it. Usually, the class containing the method is itself defined in
627this global scope, and in the next section we'll find some good
628reasons why a method would want to reference its own class!
629
630<P>
631
632<H1><A NAME="SECTION0011500000000000000000"></A><A NAME="inheritance"></A>
633<BR>
6349.5 Inheritance
635</H1>
636
637<P>
638Of course, a language feature would not be worthy of the name ``class''
639without supporting inheritance. The syntax for a derived class
640definition looks like this:
641
642<P>
643<div class="verbatim"><pre>
644class DerivedClassName(BaseClassName):
645 &lt;statement-1&gt;
646 .
647 .
648 .
649 &lt;statement-N&gt;
650</pre></div>
651
652<P>
653The name <tt class="class">BaseClassName</tt> must be defined in a scope containing
654the derived class definition. In place of a base class name, other
655arbitrary expressions are also allowed. This can be useful, for
656example, when the base class is defined in another module:
657
658<P>
659<div class="verbatim"><pre>
660class DerivedClassName(modname.BaseClassName):
661</pre></div>
662
663<P>
664Execution of a derived class definition proceeds the same as for a
665base class. When the class object is constructed, the base class is
666remembered. This is used for resolving attribute references: if a
667requested attribute is not found in the class, the search proceeds to look in the
668base class. This rule is applied recursively if the base class itself
669is derived from some other class.
670
671<P>
672There's nothing special about instantiation of derived classes:
673<code>DerivedClassName()</code> creates a new instance of the class. Method
674references are resolved as follows: the corresponding class attribute
675is searched, descending down the chain of base classes if necessary,
676and the method reference is valid if this yields a function object.
677
678<P>
679Derived classes may override methods of their base classes. Because
680methods have no special privileges when calling other methods of the
681same object, a method of a base class that calls another method
682defined in the same base class may end up calling a method of
683a derived class that overrides it. (For C++ programmers: all methods
684in Python are effectively <tt class="keyword">virtual</tt>.)
685
686<P>
687An overriding method in a derived class may in fact want to extend
688rather than simply replace the base class method of the same name.
689There is a simple way to call the base class method directly: just
690call "<tt class="samp">BaseClassName.methodname(self, arguments)</tt>". This is
691occasionally useful to clients as well. (Note that this only works if
692the base class is defined or imported directly in the global scope.)
693
694<P>
695
696<H2><A NAME="SECTION0011510000000000000000"></A><A NAME="multiple"></A>
697<BR>
6989.5.1 Multiple Inheritance
699</H2>
700
701<P>
702Python supports a limited form of multiple inheritance as well. A
703class definition with multiple base classes looks like this:
704
705<P>
706<div class="verbatim"><pre>
707class DerivedClassName(Base1, Base2, Base3):
708 &lt;statement-1&gt;
709 .
710 .
711 .
712 &lt;statement-N&gt;
713</pre></div>
714
715<P>
716The only rule necessary to explain the semantics is the resolution
717rule used for class attribute references. This is depth-first,
718left-to-right. Thus, if an attribute is not found in
719<tt class="class">DerivedClassName</tt>, it is searched in <tt class="class">Base1</tt>, then
720(recursively) in the base classes of <tt class="class">Base1</tt>, and only if it is
721not found there, it is searched in <tt class="class">Base2</tt>, and so on.
722
723<P>
724(To some people breadth first -- searching <tt class="class">Base2</tt> and
725<tt class="class">Base3</tt> before the base classes of <tt class="class">Base1</tt> -- looks more
726natural. However, this would require you to know whether a particular
727attribute of <tt class="class">Base1</tt> is actually defined in <tt class="class">Base1</tt> or in
728one of its base classes before you can figure out the consequences of
729a name conflict with an attribute of <tt class="class">Base2</tt>. The depth-first
730rule makes no differences between direct and inherited attributes of
731<tt class="class">Base1</tt>.)
732
733<P>
734It is clear that indiscriminate use of multiple inheritance is a
735maintenance nightmare, given the reliance in Python on conventions to
736avoid accidental name conflicts. A well-known problem with multiple
737inheritance is a class derived from two classes that happen to have a
738common base class. While it is easy enough to figure out what happens
739in this case (the instance will have a single copy of ``instance
740variables'' or data attributes used by the common base class), it is
741not clear that these semantics are in any way useful.
742
743<P>
744
745<H1><A NAME="SECTION0011600000000000000000"></A><A NAME="private"></A>
746<BR>
7479.6 Private Variables
748</H1>
749
750<P>
751There is limited support for class-private
752identifiers. Any identifier of the form <code>__spam</code> (at least two
753leading underscores, at most one trailing underscore) is textually
754replaced with <code>_classname__spam</code>, where <code>classname</code> is the
755current class name with leading underscore(s) stripped. This mangling
756is done without regard to the syntactic position of the identifier, so
757it can be used to define class-private instance and class variables,
758methods, variables stored in globals, and even variables stored in instances.
759private to this class on instances of <em>other</em> classes. Truncation
760may occur when the mangled name would be longer than 255 characters.
761Outside classes, or when the class name consists of only underscores,
762no mangling occurs.
763
764<P>
765Name mangling is intended to give classes an easy way to define
766``private'' instance variables and methods, without having to worry
767about instance variables defined by derived classes, or mucking with
768instance variables by code outside the class. Note that the mangling
769rules are designed mostly to avoid accidents; it still is possible for
770a determined soul to access or modify a variable that is considered
771private. This can even be useful in special circumstances, such as in
772the debugger, and that's one reason why this loophole is not closed.
773(Buglet: derivation of a class with the same name as the base class
774makes use of private variables of the base class possible.)
775
776<P>
777Notice that code passed to <code>exec</code>, <code>eval()</code> or
778<code>evalfile()</code> does not consider the classname of the invoking
779class to be the current class; this is similar to the effect of the
780<code>global</code> statement, the effect of which is likewise restricted to
781code that is byte-compiled together. The same restriction applies to
782<code>getattr()</code>, <code>setattr()</code> and <code>delattr()</code>, as well as
783when referencing <code>__dict__</code> directly.
784
785<P>
786
787<H1><A NAME="SECTION0011700000000000000000"></A><A NAME="odds"></A>
788<BR>
7899.7 Odds and Ends
790</H1>
791
792<P>
793Sometimes it is useful to have a data type similar to the Pascal
794``record'' or C ``struct'', bundling together a few named data
795items. An empty class definition will do nicely:
796
797<P>
798<div class="verbatim"><pre>
799class Employee:
800 pass
801
802john = Employee() # Create an empty employee record
803
804# Fill the fields of the record
805john.name = 'John Doe'
806john.dept = 'computer lab'
807john.salary = 1000
808</pre></div>
809
810<P>
811A piece of Python code that expects a particular abstract data type
812can often be passed a class that emulates the methods of that data
813type instead. For instance, if you have a function that formats some
814data from a file object, you can define a class with methods
815<tt class="method">read()</tt> and <tt class="method">readline()</tt> that get the data from a string
816buffer instead, and pass it as an argument.
817<P>
818Instance method objects have attributes, too: <code>m.im_self</code> is the
819instance object with the method <tt class="method">m</tt>, and <code>m.im_func</code> is the
820function object corresponding to the method.
821
822<P>
823
824<H1><A NAME="SECTION0011800000000000000000"></A><A NAME="exceptionClasses"></A>
825<BR>
8269.8 Exceptions Are Classes Too
827</H1>
828
829<P>
830User-defined exceptions are identified by classes as well. Using this
831mechanism it is possible to create extensible hierarchies of exceptions.
832
833<P>
834There are two new valid (semantic) forms for the raise statement:
835
836<P>
837<div class="verbatim"><pre>
838raise Class, instance
839
840raise instance
841</pre></div>
842
843<P>
844In the first form, <code>instance</code> must be an instance of
845<tt class="class">Class</tt> or of a class derived from it. The second form is a
846shorthand for:
847
848<P>
849<div class="verbatim"><pre>
850raise instance.__class__, instance
851</pre></div>
852
853<P>
854A class in an except clause is compatible with an exception if it is the same
855class or a base class thereof (but not the other way around -- an
856except clause listing a derived class is not compatible with a base
857class). For example, the following code will print B, C, D in that
858order:
859
860<P>
861<div class="verbatim"><pre>
862class B:
863 pass
864class C(B):
865 pass
866class D(C):
867 pass
868
869for c in [B, C, D]:
870 try:
871 raise c()
872 except D:
873 print "D"
874 except C:
875 print "C"
876 except B:
877 print "B"
878</pre></div>
879
880<P>
881Note that if the except clauses were reversed (with
882"<tt class="samp">except B</tt>" first), it would have printed B, B, B -- the first
883matching except clause is triggered.
884
885<P>
886When an error message is printed for an unhandled exception, the
887exception's class name is printed, then a colon and a space, and
888finally the instance converted to a string using the built-in function
889<tt class="function">str()</tt>.
890
891<P>
892
893<H1><A NAME="SECTION0011900000000000000000"></A><A NAME="iterators"></A>
894<BR>
8959.9 Iterators
896</H1>
897
898<P>
899By now you have probably noticed that most container objects can be looped
900over using a <tt class="keyword">for</tt> statement:
901
902<P>
903<div class="verbatim"><pre>
904for element in [1, 2, 3]:
905 print element
906for element in (1, 2, 3):
907 print element
908for key in {'one':1, 'two':2}:
909 print key
910for char in "123":
911 print char
912for line in open("myfile.txt"):
913 print line
914</pre></div>
915
916<P>
917This style of access is clear, concise, and convenient. The use of iterators
918pervades and unifies Python. Behind the scenes, the <tt class="keyword">for</tt>
919statement calls <tt class="function">iter()</tt> on the container object. The
920function returns an iterator object that defines the method
921<tt class="method">next()</tt> which accesses elements in the container one at a
922time. When there are no more elements, <tt class="method">next()</tt> raises a
923<tt class="exception">StopIteration</tt> exception which tells the <tt class="keyword">for</tt> loop
924to terminate. This example shows how it all works:
925
926<P>
927<div class="verbatim"><pre>
928&gt;&gt;&gt; s = 'abc'
929&gt;&gt;&gt; it = iter(s)
930&gt;&gt;&gt; it
931&lt;iterator object at 0x00A1DB50&gt;
932&gt;&gt;&gt; it.next()
933'a'
934&gt;&gt;&gt; it.next()
935'b'
936&gt;&gt;&gt; it.next()
937'c'
938&gt;&gt;&gt; it.next()
939
940Traceback (most recent call last):
941 File "&lt;stdin&gt;", line 1, in ?
942 it.next()
943StopIteration
944</pre></div>
945
946<P>
947Having seen the mechanics behind the iterator protocol, it is easy to add
948iterator behavior to your classes. Define a <tt class="method">__iter__()</tt> method
949which returns an object with a <tt class="method">next()</tt> method. If the class defines
950<tt class="method">next()</tt>, then <tt class="method">__iter__()</tt> can just return <code>self</code>:
951
952<P>
953<div class="verbatim"><pre>
954class Reverse:
955 "Iterator for looping over a sequence backwards"
956 def __init__(self, data):
957 self.data = data
958 self.index = len(data)
959 def __iter__(self):
960 return self
961 def next(self):
962 if self.index == 0:
963 raise StopIteration
964 self.index = self.index - 1
965 return self.data[self.index]
966
967&gt;&gt;&gt; for char in Reverse('spam'):
968... print char
969...
970m
971a
972p
973s
974</pre></div>
975
976<P>
977
978<H1><A NAME="SECTION00111000000000000000000"></A><A NAME="generators"></A>
979<BR>
9809.10 Generators
981</H1>
982
983<P>
984Generators are a simple and powerful tool for creating iterators. They are
985written like regular functions but use the <tt class="keyword">yield</tt> statement whenever
986they want to return data. Each time <tt class="method">next()</tt> is called, the
987generator resumes where it left-off (it remembers all the data values and
988which statement was last executed). An example shows that generators can
989be trivially easy to create:
990
991<P>
992<div class="verbatim"><pre>
993def reverse(data):
994 for index in range(len(data)-1, -1, -1):
995 yield data[index]
996
997&gt;&gt;&gt; for char in reverse('golf'):
998... print char
999...
1000f
1001l
1002o
1003g
1004</pre></div>
1005
1006<P>
1007Anything that can be done with generators can also be done with class based
1008iterators as described in the previous section. What makes generators so
1009compact is that the <tt class="method">__iter__()</tt> and <tt class="method">next()</tt> methods are
1010created automatically.
1011
1012<P>
1013Another key feature is that the local variables and execution state
1014are automatically saved between calls. This made the function easier to write
1015and much more clear than an approach using instance variables like
1016<code>self.index</code> and <code>self.data</code>.
1017
1018<P>
1019In addition to automatic method creation and saving program state, when
1020generators terminate, they automatically raise <tt class="exception">StopIteration</tt>.
1021In combination, these features make it easy to create iterators with no
1022more effort than writing a regular function.
1023
1024<P>
1025
1026<H1><A NAME="SECTION00111100000000000000000"></A><A NAME="genexps"></A>
1027<BR>
10289.11 Generator Expressions
1029</H1>
1030
1031<P>
1032Some simple generators can be coded succinctly as expressions using a syntax
1033similar to list comprehensions but with parentheses instead of brackets. These
1034expressions are designed for situations where the generator is used right
1035away by an enclosing function. Generator expressions are more compact but
1036less versatile than full generator definitions and tend to be more memory
1037friendly than equivalent list comprehensions.
1038
1039<P>
1040Examples:
1041
1042<P>
1043<div class="verbatim"><pre>
1044&gt;&gt;&gt; sum(i*i for i in range(10)) # sum of squares
1045285
1046
1047&gt;&gt;&gt; xvec = [10, 20, 30]
1048&gt;&gt;&gt; yvec = [7, 5, 3]
1049&gt;&gt;&gt; sum(x*y for x,y in zip(xvec, yvec)) # dot product
1050260
1051
1052&gt;&gt;&gt; from math import pi, sin
1053&gt;&gt;&gt; sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91))
1054
1055&gt;&gt;&gt; unique_words = set(word for line in page for word in line.split())
1056
1057&gt;&gt;&gt; valedictorian = max((student.gpa, student.name) for student in graduates)
1058
1059&gt;&gt;&gt; data = 'golf'
1060&gt;&gt;&gt; list(data[i] for i in range(len(data)-1,-1,-1))
1061['f', 'l', 'o', 'g']
1062</pre></div>
1063
1064<P>
1065<BR><HR><H4>Footnotes</H4>
1066<DL>
1067<DT><A NAME="foot1849">... namespace!</A><A
1068 HREF="node11.html#tex2html5"><SUP>9.1</SUP></A></DT>
1069<DD>
1070 Except for one thing. Module objects have a secret read-only
1071 attribute called <tt class="member">__dict__</tt> which returns the dictionary
1072 used to implement the module's namespace; the name
1073 <tt class="member">__dict__</tt> is an attribute but not a global name.
1074 Obviously, using this violates the abstraction of namespace
1075 implementation, and should be restricted to things like
1076 post-mortem debuggers.
1077
1078
1079</DD>
1080</DL>
1081<DIV CLASS="navigation">
1082<div class='online-navigation'>
1083<p></p><hr />
1084<table align="center" width="100%" cellpadding="0" cellspacing="2">
1085<tr>
1086<td class='online-navigation'><a rel="prev" title="8. Errors and Exceptions"
1087 href="node10.html"><img src='../icons/previous.png'
1088 border='0' height='32' alt='Previous Page' width='32' /></A></td>
1089<td class='online-navigation'><a rel="parent" title="Python Tutorial"
1090 href="tut.html"><img src='../icons/up.png'
1091 border='0' height='32' alt='Up One Level' width='32' /></A></td>
1092<td class='online-navigation'><a rel="next" title="10. Brief Tour of"
1093 href="node12.html"><img src='../icons/next.png'
1094 border='0' height='32' alt='Next Page' width='32' /></A></td>
1095<td align="center" width="100%">Python Tutorial</td>
1096<td class='online-navigation'><a rel="contents" title="Table of Contents"
1097 href="node2.html"><img src='../icons/contents.png'
1098 border='0' height='32' alt='Contents' width='32' /></A></td>
1099<td class='online-navigation'><img src='../icons/blank.png'
1100 border='0' height='32' alt='' width='32' /></td>
1101<td class='online-navigation'><a rel="index" title="Index"
1102 href="node19.html"><img src='../icons/index.png'
1103 border='0' height='32' alt='Index' width='32' /></A></td>
1104</tr></table>
1105<div class='online-navigation'>
1106<b class="navlabel">Previous:</b>
1107<a class="sectref" rel="prev" href="node10.html">8. Errors and Exceptions</A>
1108<b class="navlabel">Up:</b>
1109<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
1110<b class="navlabel">Next:</b>
1111<a class="sectref" rel="next" href="node12.html">10. Brief Tour of</A>
1112</div>
1113</div>
1114<hr />
1115<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
1116</DIV>
1117<!--End of Navigation Panel-->
1118<ADDRESS>
1119See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
1120</ADDRESS>
1121</BODY>
1122</HTML>