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