Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | .. _tut-classes: |
| 2 | |
| 3 | ******* |
| 4 | Classes |
| 5 | ******* |
| 6 | |
| 7 | Python's class mechanism adds classes to the language with a minimum of new |
| 8 | syntax and semantics. It is a mixture of the class mechanisms found in C++ and |
| 9 | Modula-3. As is true for modules, classes in Python do not put an absolute |
| 10 | barrier between definition and user, but rather rely on the politeness of the |
| 11 | user not to "break into the definition." The most important features of classes |
| 12 | are retained with full power, however: the class inheritance mechanism allows |
| 13 | multiple base classes, a derived class can override any methods of its base |
| 14 | class or classes, and a method can call the method of a base class with the same |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 15 | name. Objects can contain an arbitrary amount of data. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 16 | |
| 17 | In C++ terminology, all class members (including the data members) are *public*, |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 18 | and all member functions are *virtual*. As in Modula-3, there are no shorthands |
| 19 | for referencing the object's members from its methods: the method function is |
| 20 | declared with an explicit first argument representing the object, which is |
| 21 | provided implicitly by the call. As in Smalltalk, classes themselves are |
| 22 | objects. This provides semantics for importing and renaming. Unlike C++ and |
| 23 | Modula-3, built-in types can be used as base classes for extension by the user. |
| 24 | Also, like in C++, most built-in operators with special syntax (arithmetic |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 25 | operators, subscripting etc.) can be redefined for class instances. |
| 26 | |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 27 | (Lacking universally accepted terminology to talk about classes, I will make |
| 28 | occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 29 | its object-oriented semantics are closer to those of Python than C++, but I |
| 30 | expect that few readers have heard of it.) |
| 31 | |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 32 | |
| 33 | .. _tut-object: |
| 34 | |
| 35 | A Word About Names and Objects |
| 36 | ============================== |
| 37 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 38 | Objects have individuality, and multiple names (in multiple scopes) can be bound |
| 39 | to the same object. This is known as aliasing in other languages. This is |
| 40 | usually not appreciated on a first glance at Python, and can be safely ignored |
| 41 | when dealing with immutable basic types (numbers, strings, tuples). However, |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 42 | aliasing has a possibly surprising effect on the semantics of Python code |
| 43 | involving mutable objects such as lists, dictionaries, and most other types. |
| 44 | This is usually used to the benefit of the program, since aliases behave like |
| 45 | pointers in some respects. For example, passing an object is cheap since only a |
| 46 | pointer is passed by the implementation; and if a function modifies an object |
| 47 | passed as an argument, the caller will see the change --- this eliminates the |
| 48 | need for two different argument passing mechanisms as in Pascal. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 49 | |
| 50 | |
| 51 | .. _tut-scopes: |
| 52 | |
| 53 | Python Scopes and Name Spaces |
| 54 | ============================= |
| 55 | |
| 56 | Before introducing classes, I first have to tell you something about Python's |
| 57 | scope rules. Class definitions play some neat tricks with namespaces, and you |
| 58 | need to know how scopes and namespaces work to fully understand what's going on. |
| 59 | Incidentally, knowledge about this subject is useful for any advanced Python |
| 60 | programmer. |
| 61 | |
| 62 | Let's begin with some definitions. |
| 63 | |
| 64 | A *namespace* is a mapping from names to objects. Most namespaces are currently |
| 65 | implemented as Python dictionaries, but that's normally not noticeable in any |
| 66 | way (except for performance), and it may change in the future. Examples of |
| 67 | namespaces are: the set of built-in names (functions such as :func:`abs`, and |
| 68 | built-in exception names); the global names in a module; and the local names in |
| 69 | a function invocation. In a sense the set of attributes of an object also form |
| 70 | a namespace. The important thing to know about namespaces is that there is |
| 71 | absolutely no relation between names in different namespaces; for instance, two |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 72 | different modules may both define a function ``maximize`` without confusion --- |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 73 | users of the modules must prefix it with the module name. |
| 74 | |
| 75 | By the way, I use the word *attribute* for any name following a dot --- for |
| 76 | example, in the expression ``z.real``, ``real`` is an attribute of the object |
| 77 | ``z``. Strictly speaking, references to names in modules are attribute |
| 78 | references: in the expression ``modname.funcname``, ``modname`` is a module |
| 79 | object and ``funcname`` is an attribute of it. In this case there happens to be |
| 80 | a straightforward mapping between the module's attributes and the global names |
| 81 | defined in the module: they share the same namespace! [#]_ |
| 82 | |
| 83 | Attributes may be read-only or writable. In the latter case, assignment to |
| 84 | attributes is possible. Module attributes are writable: you can write |
| 85 | ``modname.the_answer = 42``. Writable attributes may also be deleted with the |
| 86 | :keyword:`del` statement. For example, ``del modname.the_answer`` will remove |
| 87 | the attribute :attr:`the_answer` from the object named by ``modname``. |
| 88 | |
| 89 | Name spaces are created at different moments and have different lifetimes. The |
| 90 | namespace containing the built-in names is created when the Python interpreter |
| 91 | starts up, and is never deleted. The global namespace for a module is created |
| 92 | when the module definition is read in; normally, module namespaces also last |
| 93 | until the interpreter quits. The statements executed by the top-level |
| 94 | invocation of the interpreter, either read from a script file or interactively, |
| 95 | are considered part of a module called :mod:`__main__`, so they have their own |
| 96 | global namespace. (The built-in names actually also live in a module; this is |
| 97 | called :mod:`__builtin__`.) |
| 98 | |
| 99 | The local namespace for a function is created when the function is called, and |
| 100 | deleted when the function returns or raises an exception that is not handled |
| 101 | within the function. (Actually, forgetting would be a better way to describe |
| 102 | what actually happens.) Of course, recursive invocations each have their own |
| 103 | local namespace. |
| 104 | |
| 105 | A *scope* is a textual region of a Python program where a namespace is directly |
| 106 | accessible. "Directly accessible" here means that an unqualified reference to a |
| 107 | name attempts to find the name in the namespace. |
| 108 | |
| 109 | Although scopes are determined statically, they are used dynamically. At any |
| 110 | time during execution, there are at least three nested scopes whose namespaces |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 111 | are directly accessible: |
| 112 | |
| 113 | * the innermost scope, which is searched first, contains the local names |
| 114 | * the scopes of any enclosing functions, which are searched starting with the |
| 115 | nearest enclosing scope, contains non-local, but also non-global names |
| 116 | * the next-to-last scope contains the current module's global names |
| 117 | * the outermost scope (searched last) is the namespace containing built-in names |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 118 | |
| 119 | If a name is declared global, then all references and assignments go directly to |
| 120 | the middle scope containing the module's global names. Otherwise, all variables |
| 121 | found outside of the innermost scope are read-only (an attempt to write to such |
| 122 | a variable will simply create a *new* local variable in the innermost scope, |
| 123 | leaving the identically named outer variable unchanged). |
| 124 | |
| 125 | Usually, the local scope references the local names of the (textually) current |
| 126 | function. Outside functions, the local scope references the same namespace as |
| 127 | the global scope: the module's namespace. Class definitions place yet another |
| 128 | namespace in the local scope. |
| 129 | |
| 130 | It is important to realize that scopes are determined textually: the global |
| 131 | scope of a function defined in a module is that module's namespace, no matter |
| 132 | from where or by what alias the function is called. On the other hand, the |
| 133 | actual search for names is done dynamically, at run time --- however, the |
| 134 | language definition is evolving towards static name resolution, at "compile" |
| 135 | time, so don't rely on dynamic name resolution! (In fact, local variables are |
| 136 | already determined statically.) |
| 137 | |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 138 | A special quirk of Python is that -- if no :keyword:`global` statement is in |
| 139 | effect -- assignments to names always go into the innermost scope. Assignments |
| 140 | do not copy data --- they just bind names to objects. The same is true for |
| 141 | deletions: the statement ``del x`` removes the binding of ``x`` from the |
| 142 | namespace referenced by the local scope. In fact, all operations that introduce |
| 143 | new names use the local scope: in particular, :keyword:`import` statements and |
| 144 | function definitions bind the module or function name in the local scope. (The |
| 145 | :keyword:`global` statement can be used to indicate that particular variables |
| 146 | live in the global scope.) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 147 | |
| 148 | |
| 149 | .. _tut-firstclasses: |
| 150 | |
| 151 | A First Look at Classes |
| 152 | ======================= |
| 153 | |
| 154 | Classes introduce a little bit of new syntax, three new object types, and some |
| 155 | new semantics. |
| 156 | |
| 157 | |
| 158 | .. _tut-classdefinition: |
| 159 | |
| 160 | Class Definition Syntax |
| 161 | ----------------------- |
| 162 | |
| 163 | The simplest form of class definition looks like this:: |
| 164 | |
| 165 | class ClassName: |
| 166 | <statement-1> |
| 167 | . |
| 168 | . |
| 169 | . |
| 170 | <statement-N> |
| 171 | |
| 172 | Class definitions, like function definitions (:keyword:`def` statements) must be |
| 173 | executed before they have any effect. (You could conceivably place a class |
| 174 | definition in a branch of an :keyword:`if` statement, or inside a function.) |
| 175 | |
| 176 | In practice, the statements inside a class definition will usually be function |
| 177 | definitions, but other statements are allowed, and sometimes useful --- we'll |
| 178 | come back to this later. The function definitions inside a class normally have |
| 179 | a peculiar form of argument list, dictated by the calling conventions for |
| 180 | methods --- again, this is explained later. |
| 181 | |
| 182 | When a class definition is entered, a new namespace is created, and used as the |
| 183 | local scope --- thus, all assignments to local variables go into this new |
| 184 | namespace. In particular, function definitions bind the name of the new |
| 185 | function here. |
| 186 | |
| 187 | When a class definition is left normally (via the end), a *class object* is |
| 188 | created. This is basically a wrapper around the contents of the namespace |
| 189 | created by the class definition; we'll learn more about class objects in the |
| 190 | next section. The original local scope (the one in effect just before the class |
| 191 | definition was entered) is reinstated, and the class object is bound here to the |
| 192 | class name given in the class definition header (:class:`ClassName` in the |
| 193 | example). |
| 194 | |
| 195 | |
| 196 | .. _tut-classobjects: |
| 197 | |
| 198 | Class Objects |
| 199 | ------------- |
| 200 | |
| 201 | Class objects support two kinds of operations: attribute references and |
| 202 | instantiation. |
| 203 | |
| 204 | *Attribute references* use the standard syntax used for all attribute references |
| 205 | in Python: ``obj.name``. Valid attribute names are all the names that were in |
| 206 | the class's namespace when the class object was created. So, if the class |
| 207 | definition looked like this:: |
| 208 | |
| 209 | class MyClass: |
Georg Brandl | 3ce0dee | 2008-09-13 17:18:11 +0000 | [diff] [blame] | 210 | """A simple example class""" |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 211 | i = 12345 |
| 212 | def f(self): |
| 213 | return 'hello world' |
| 214 | |
| 215 | then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, returning |
| 216 | an integer and a function object, respectively. Class attributes can also be |
| 217 | assigned to, so you can change the value of ``MyClass.i`` by assignment. |
| 218 | :attr:`__doc__` is also a valid attribute, returning the docstring belonging to |
| 219 | the class: ``"A simple example class"``. |
| 220 | |
| 221 | Class *instantiation* uses function notation. Just pretend that the class |
| 222 | object is a parameterless function that returns a new instance of the class. |
| 223 | For example (assuming the above class):: |
| 224 | |
| 225 | x = MyClass() |
| 226 | |
| 227 | creates a new *instance* of the class and assigns this object to the local |
| 228 | variable ``x``. |
| 229 | |
| 230 | The instantiation operation ("calling" a class object) creates an empty object. |
| 231 | Many classes like to create objects with instances customized to a specific |
| 232 | initial state. Therefore a class may define a special method named |
| 233 | :meth:`__init__`, like this:: |
| 234 | |
| 235 | def __init__(self): |
| 236 | self.data = [] |
| 237 | |
| 238 | When a class defines an :meth:`__init__` method, class instantiation |
| 239 | automatically invokes :meth:`__init__` for the newly-created class instance. So |
| 240 | in this example, a new, initialized instance can be obtained by:: |
| 241 | |
| 242 | x = MyClass() |
| 243 | |
| 244 | Of course, the :meth:`__init__` method may have arguments for greater |
| 245 | flexibility. In that case, arguments given to the class instantiation operator |
| 246 | are passed on to :meth:`__init__`. For example, :: |
| 247 | |
| 248 | >>> class Complex: |
| 249 | ... def __init__(self, realpart, imagpart): |
| 250 | ... self.r = realpart |
| 251 | ... self.i = imagpart |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 252 | ... |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 253 | >>> x = Complex(3.0, -4.5) |
| 254 | >>> x.r, x.i |
| 255 | (3.0, -4.5) |
| 256 | |
| 257 | |
| 258 | .. _tut-instanceobjects: |
| 259 | |
| 260 | Instance Objects |
| 261 | ---------------- |
| 262 | |
| 263 | Now what can we do with instance objects? The only operations understood by |
| 264 | instance objects are attribute references. There are two kinds of valid |
| 265 | attribute names, data attributes and methods. |
| 266 | |
| 267 | *data attributes* correspond to "instance variables" in Smalltalk, and to "data |
| 268 | members" in C++. Data attributes need not be declared; like local variables, |
| 269 | they spring into existence when they are first assigned to. For example, if |
| 270 | ``x`` is the instance of :class:`MyClass` created above, the following piece of |
| 271 | code will print the value ``16``, without leaving a trace:: |
| 272 | |
| 273 | x.counter = 1 |
| 274 | while x.counter < 10: |
| 275 | x.counter = x.counter * 2 |
| 276 | print x.counter |
| 277 | del x.counter |
| 278 | |
| 279 | The other kind of instance attribute reference is a *method*. A method is a |
| 280 | function that "belongs to" an object. (In Python, the term method is not unique |
| 281 | to class instances: other object types can have methods as well. For example, |
| 282 | list objects have methods called append, insert, remove, sort, and so on. |
| 283 | However, in the following discussion, we'll use the term method exclusively to |
| 284 | mean methods of class instance objects, unless explicitly stated otherwise.) |
| 285 | |
| 286 | .. index:: object: method |
| 287 | |
| 288 | Valid method names of an instance object depend on its class. By definition, |
| 289 | all attributes of a class that are function objects define corresponding |
| 290 | methods of its instances. So in our example, ``x.f`` is a valid method |
| 291 | reference, since ``MyClass.f`` is a function, but ``x.i`` is not, since |
| 292 | ``MyClass.i`` is not. But ``x.f`` is not the same thing as ``MyClass.f`` --- it |
| 293 | is a *method object*, not a function object. |
| 294 | |
| 295 | |
| 296 | .. _tut-methodobjects: |
| 297 | |
| 298 | Method Objects |
| 299 | -------------- |
| 300 | |
| 301 | Usually, a method is called right after it is bound:: |
| 302 | |
| 303 | x.f() |
| 304 | |
| 305 | In the :class:`MyClass` example, this will return the string ``'hello world'``. |
| 306 | However, it is not necessary to call a method right away: ``x.f`` is a method |
| 307 | object, and can be stored away and called at a later time. For example:: |
| 308 | |
| 309 | xf = x.f |
| 310 | while True: |
| 311 | print xf() |
| 312 | |
| 313 | will continue to print ``hello world`` until the end of time. |
| 314 | |
| 315 | What exactly happens when a method is called? You may have noticed that |
| 316 | ``x.f()`` was called without an argument above, even though the function |
| 317 | definition for :meth:`f` specified an argument. What happened to the argument? |
| 318 | Surely Python raises an exception when a function that requires an argument is |
| 319 | called without any --- even if the argument isn't actually used... |
| 320 | |
| 321 | Actually, you may have guessed the answer: the special thing about methods is |
| 322 | that the object is passed as the first argument of the function. In our |
| 323 | example, the call ``x.f()`` is exactly equivalent to ``MyClass.f(x)``. In |
| 324 | general, calling a method with a list of *n* arguments is equivalent to calling |
| 325 | the corresponding function with an argument list that is created by inserting |
| 326 | the method's object before the first argument. |
| 327 | |
| 328 | If you still don't understand how methods work, a look at the implementation can |
| 329 | perhaps clarify matters. When an instance attribute is referenced that isn't a |
| 330 | data attribute, its class is searched. If the name denotes a valid class |
| 331 | attribute that is a function object, a method object is created by packing |
| 332 | (pointers to) the instance object and the function object just found together in |
| 333 | an abstract object: this is the method object. When the method object is called |
| 334 | with an argument list, it is unpacked again, a new argument list is constructed |
| 335 | from the instance object and the original argument list, and the function object |
| 336 | is called with this new argument list. |
| 337 | |
| 338 | |
| 339 | .. _tut-remarks: |
| 340 | |
| 341 | Random Remarks |
| 342 | ============== |
| 343 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 344 | .. These should perhaps be placed more carefully... |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 345 | |
| 346 | Data attributes override method attributes with the same name; to avoid |
| 347 | accidental name conflicts, which may cause hard-to-find bugs in large programs, |
| 348 | it is wise to use some kind of convention that minimizes the chance of |
| 349 | conflicts. Possible conventions include capitalizing method names, prefixing |
| 350 | data attribute names with a small unique string (perhaps just an underscore), or |
| 351 | using verbs for methods and nouns for data attributes. |
| 352 | |
| 353 | Data attributes may be referenced by methods as well as by ordinary users |
| 354 | ("clients") of an object. In other words, classes are not usable to implement |
| 355 | pure abstract data types. In fact, nothing in Python makes it possible to |
| 356 | enforce data hiding --- it is all based upon convention. (On the other hand, |
| 357 | the Python implementation, written in C, can completely hide implementation |
| 358 | details and control access to an object if necessary; this can be used by |
| 359 | extensions to Python written in C.) |
| 360 | |
| 361 | Clients should use data attributes with care --- clients may mess up invariants |
| 362 | maintained by the methods by stamping on their data attributes. Note that |
| 363 | clients may add data attributes of their own to an instance object without |
| 364 | affecting the validity of the methods, as long as name conflicts are avoided --- |
| 365 | again, a naming convention can save a lot of headaches here. |
| 366 | |
| 367 | There is no shorthand for referencing data attributes (or other methods!) from |
| 368 | within methods. I find that this actually increases the readability of methods: |
| 369 | there is no chance of confusing local variables and instance variables when |
| 370 | glancing through a method. |
| 371 | |
| 372 | Often, the first argument of a method is called ``self``. This is nothing more |
| 373 | than a convention: the name ``self`` has absolutely no special meaning to |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 374 | Python. Note, however, that by not following the convention your code may be |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 375 | less readable to other Python programmers, and it is also conceivable that a |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 376 | *class browser* program might be written that relies upon such a convention. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 377 | |
| 378 | Any function object that is a class attribute defines a method for instances of |
| 379 | that class. It is not necessary that the function definition is textually |
| 380 | enclosed in the class definition: assigning a function object to a local |
| 381 | variable in the class is also ok. For example:: |
| 382 | |
| 383 | # Function defined outside the class |
| 384 | def f1(self, x, y): |
| 385 | return min(x, x+y) |
| 386 | |
| 387 | class C: |
| 388 | f = f1 |
| 389 | def g(self): |
| 390 | return 'hello world' |
| 391 | h = g |
| 392 | |
| 393 | Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to |
| 394 | function objects, and consequently they are all methods of instances of |
| 395 | :class:`C` --- ``h`` being exactly equivalent to ``g``. Note that this practice |
| 396 | usually only serves to confuse the reader of a program. |
| 397 | |
| 398 | Methods may call other methods by using method attributes of the ``self`` |
| 399 | argument:: |
| 400 | |
| 401 | class Bag: |
| 402 | def __init__(self): |
| 403 | self.data = [] |
| 404 | def add(self, x): |
| 405 | self.data.append(x) |
| 406 | def addtwice(self, x): |
| 407 | self.add(x) |
| 408 | self.add(x) |
| 409 | |
| 410 | Methods may reference global names in the same way as ordinary functions. The |
| 411 | global scope associated with a method is the module containing the class |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 412 | definition. (The class itself is never used as a global scope.) While one |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 413 | rarely encounters a good reason for using global data in a method, there are |
| 414 | many legitimate uses of the global scope: for one thing, functions and modules |
| 415 | imported into the global scope can be used by methods, as well as functions and |
| 416 | classes defined in it. Usually, the class containing the method is itself |
| 417 | defined in this global scope, and in the next section we'll find some good |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 418 | reasons why a method would want to reference its own class. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 419 | |
Georg Brandl | 6c45dc1 | 2008-03-06 07:31:34 +0000 | [diff] [blame] | 420 | Each value is an object, and therefore has a *class* (also called its *type*). |
| 421 | It is stored as ``object.__class__``. |
| 422 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 423 | |
| 424 | .. _tut-inheritance: |
| 425 | |
| 426 | Inheritance |
| 427 | =========== |
| 428 | |
| 429 | Of course, a language feature would not be worthy of the name "class" without |
| 430 | supporting inheritance. The syntax for a derived class definition looks like |
| 431 | this:: |
| 432 | |
| 433 | class DerivedClassName(BaseClassName): |
| 434 | <statement-1> |
| 435 | . |
| 436 | . |
| 437 | . |
| 438 | <statement-N> |
| 439 | |
| 440 | The name :class:`BaseClassName` must be defined in a scope containing the |
| 441 | derived class definition. In place of a base class name, other arbitrary |
| 442 | expressions are also allowed. This can be useful, for example, when the base |
| 443 | class is defined in another module:: |
| 444 | |
| 445 | class DerivedClassName(modname.BaseClassName): |
| 446 | |
| 447 | Execution of a derived class definition proceeds the same as for a base class. |
| 448 | When the class object is constructed, the base class is remembered. This is |
| 449 | used for resolving attribute references: if a requested attribute is not found |
| 450 | in the class, the search proceeds to look in the base class. This rule is |
| 451 | applied recursively if the base class itself is derived from some other class. |
| 452 | |
| 453 | There's nothing special about instantiation of derived classes: |
| 454 | ``DerivedClassName()`` creates a new instance of the class. Method references |
| 455 | are resolved as follows: the corresponding class attribute is searched, |
| 456 | descending down the chain of base classes if necessary, and the method reference |
| 457 | is valid if this yields a function object. |
| 458 | |
| 459 | Derived classes may override methods of their base classes. Because methods |
| 460 | have no special privileges when calling other methods of the same object, a |
| 461 | method of a base class that calls another method defined in the same base class |
| 462 | may end up calling a method of a derived class that overrides it. (For C++ |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 463 | programmers: all methods in Python are effectively ``virtual``.) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 464 | |
| 465 | An overriding method in a derived class may in fact want to extend rather than |
| 466 | simply replace the base class method of the same name. There is a simple way to |
| 467 | call the base class method directly: just call ``BaseClassName.methodname(self, |
| 468 | arguments)``. This is occasionally useful to clients as well. (Note that this |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 469 | only works if the base class is accessible as ``BaseClassName`` in the global |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 470 | scope.) |
| 471 | |
Mark Dickinson | 3e4caeb | 2009-02-21 20:27:01 +0000 | [diff] [blame] | 472 | Python has two built-in functions that work with inheritance: |
Georg Brandl | 6c45dc1 | 2008-03-06 07:31:34 +0000 | [diff] [blame] | 473 | |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 474 | * Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)`` |
Georg Brandl | 6c45dc1 | 2008-03-06 07:31:34 +0000 | [diff] [blame] | 475 | will be ``True`` only if ``obj.__class__`` is :class:`int` or some class |
| 476 | derived from :class:`int`. |
| 477 | |
| 478 | * Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)`` |
| 479 | is ``True`` since :class:`bool` is a subclass of :class:`int`. However, |
| 480 | ``issubclass(unicode, str)`` is ``False`` since :class:`unicode` is not a |
| 481 | subclass of :class:`str` (they only share a common ancestor, |
| 482 | :class:`basestring`). |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 483 | |
Georg Brandl | 6c45dc1 | 2008-03-06 07:31:34 +0000 | [diff] [blame] | 484 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 485 | |
| 486 | .. _tut-multiple: |
| 487 | |
| 488 | Multiple Inheritance |
| 489 | -------------------- |
| 490 | |
| 491 | Python supports a limited form of multiple inheritance as well. A class |
| 492 | definition with multiple base classes looks like this:: |
| 493 | |
| 494 | class DerivedClassName(Base1, Base2, Base3): |
| 495 | <statement-1> |
| 496 | . |
| 497 | . |
| 498 | . |
| 499 | <statement-N> |
| 500 | |
| 501 | For old-style classes, the only rule is depth-first, left-to-right. Thus, if an |
| 502 | attribute is not found in :class:`DerivedClassName`, it is searched in |
| 503 | :class:`Base1`, then (recursively) in the base classes of :class:`Base1`, and |
| 504 | only if it is not found there, it is searched in :class:`Base2`, and so on. |
| 505 | |
| 506 | (To some people breadth first --- searching :class:`Base2` and :class:`Base3` |
| 507 | before the base classes of :class:`Base1` --- looks more natural. However, this |
| 508 | would require you to know whether a particular attribute of :class:`Base1` is |
| 509 | actually defined in :class:`Base1` or in one of its base classes before you can |
| 510 | figure out the consequences of a name conflict with an attribute of |
| 511 | :class:`Base2`. The depth-first rule makes no differences between direct and |
| 512 | inherited attributes of :class:`Base1`.) |
| 513 | |
Georg Brandl | a739503 | 2007-10-21 12:15:05 +0000 | [diff] [blame] | 514 | For :term:`new-style class`\es, the method resolution order changes dynamically |
| 515 | to support cooperative calls to :func:`super`. This approach is known in some |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 516 | other multiple-inheritance languages as call-next-method and is more powerful |
| 517 | than the super call found in single-inheritance languages. |
| 518 | |
| 519 | With new-style classes, dynamic ordering is necessary because all cases of |
| 520 | multiple inheritance exhibit one or more diamond relationships (where one at |
| 521 | least one of the parent classes can be accessed through multiple paths from the |
| 522 | bottommost class). For example, all new-style classes inherit from |
| 523 | :class:`object`, so any case of multiple inheritance provides more than one path |
| 524 | to reach :class:`object`. To keep the base classes from being accessed more |
| 525 | than once, the dynamic algorithm linearizes the search order in a way that |
| 526 | preserves the left-to-right ordering specified in each class, that calls each |
| 527 | parent only once, and that is monotonic (meaning that a class can be subclassed |
| 528 | without affecting the precedence order of its parents). Taken together, these |
| 529 | properties make it possible to design reliable and extensible classes with |
| 530 | multiple inheritance. For more detail, see |
| 531 | http://www.python.org/download/releases/2.3/mro/. |
| 532 | |
| 533 | |
| 534 | .. _tut-private: |
| 535 | |
| 536 | Private Variables |
| 537 | ================= |
| 538 | |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 539 | "Private" instance variables that cannot be accessed except from inside an |
| 540 | object, don't exist in Python. However, there is a convention that is followed |
| 541 | by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should |
| 542 | be treated as a non-public part of the API (whether it is a function, a method |
| 543 | or a data member). It should be considered an implementation detail and subject |
| 544 | to change without notice. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 545 | |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 546 | Since there is a valid use-case for class-private members (namely to avoid name |
| 547 | clashes of names with names defined by subclasses), there is limited support for |
| 548 | such a mechanism, called :dfn:`name mangling`. Any identifier of the form |
| 549 | ``__spam`` (at least two leading underscores, at most one trailing underscore) |
| 550 | is textually replaced with ``_classname__spam``, where ``classname`` is the |
| 551 | current class name with leading underscore(s) stripped. This mangling is done |
Georg Brandl | aa66a96 | 2009-08-13 12:57:25 +0000 | [diff] [blame^] | 552 | without regard to the syntactic position of the identifier, as long as it |
| 553 | occurs within the definition of a class. |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 554 | |
| 555 | Note that the mangling rules are designed mostly to avoid accidents; it still is |
| 556 | possible to access or modify a variable that is considered private. This can |
| 557 | even be useful in special circumstances, such as in the debugger. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 558 | |
| 559 | Notice that code passed to ``exec``, ``eval()`` or ``execfile()`` does not |
| 560 | consider the classname of the invoking class to be the current class; this is |
| 561 | similar to the effect of the ``global`` statement, the effect of which is |
| 562 | likewise restricted to code that is byte-compiled together. The same |
| 563 | restriction applies to ``getattr()``, ``setattr()`` and ``delattr()``, as well |
| 564 | as when referencing ``__dict__`` directly. |
| 565 | |
| 566 | |
| 567 | .. _tut-odds: |
| 568 | |
| 569 | Odds and Ends |
| 570 | ============= |
| 571 | |
| 572 | Sometimes it is useful to have a data type similar to the Pascal "record" or C |
| 573 | "struct", bundling together a few named data items. An empty class definition |
| 574 | will do nicely:: |
| 575 | |
| 576 | class Employee: |
| 577 | pass |
| 578 | |
| 579 | john = Employee() # Create an empty employee record |
| 580 | |
| 581 | # Fill the fields of the record |
| 582 | john.name = 'John Doe' |
| 583 | john.dept = 'computer lab' |
| 584 | john.salary = 1000 |
| 585 | |
| 586 | A piece of Python code that expects a particular abstract data type can often be |
| 587 | passed a class that emulates the methods of that data type instead. For |
| 588 | instance, if you have a function that formats some data from a file object, you |
| 589 | can define a class with methods :meth:`read` and :meth:`readline` that get the |
| 590 | data from a string buffer instead, and pass it as an argument. |
| 591 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 592 | .. (Unfortunately, this technique has its limitations: a class can't define |
| 593 | operations that are accessed by special syntax such as sequence subscripting |
| 594 | or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will |
| 595 | not cause the interpreter to read further input from it.) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 596 | |
| 597 | Instance method objects have attributes, too: ``m.im_self`` is the instance |
| 598 | object with the method :meth:`m`, and ``m.im_func`` is the function object |
| 599 | corresponding to the method. |
| 600 | |
| 601 | |
| 602 | .. _tut-exceptionclasses: |
| 603 | |
| 604 | Exceptions Are Classes Too |
| 605 | ========================== |
| 606 | |
| 607 | User-defined exceptions are identified by classes as well. Using this mechanism |
| 608 | it is possible to create extensible hierarchies of exceptions. |
| 609 | |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 610 | There are two new valid (semantic) forms for the :keyword:`raise` statement:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 611 | |
| 612 | raise Class, instance |
| 613 | |
| 614 | raise instance |
| 615 | |
| 616 | In the first form, ``instance`` must be an instance of :class:`Class` or of a |
| 617 | class derived from it. The second form is a shorthand for:: |
| 618 | |
| 619 | raise instance.__class__, instance |
| 620 | |
Georg Brandl | 4938fef | 2009-07-29 17:50:25 +0000 | [diff] [blame] | 621 | A class in an :keyword:`except` clause is compatible with an exception if it is |
| 622 | the same class or a base class thereof (but not the other way around --- an |
| 623 | except clause listing a derived class is not compatible with a base class). For |
| 624 | example, the following code will print B, C, D in that order:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 625 | |
| 626 | class B: |
| 627 | pass |
| 628 | class C(B): |
| 629 | pass |
| 630 | class D(C): |
| 631 | pass |
| 632 | |
| 633 | for c in [B, C, D]: |
| 634 | try: |
| 635 | raise c() |
| 636 | except D: |
| 637 | print "D" |
| 638 | except C: |
| 639 | print "C" |
| 640 | except B: |
| 641 | print "B" |
| 642 | |
| 643 | Note that if the except clauses were reversed (with ``except B`` first), it |
| 644 | would have printed B, B, B --- the first matching except clause is triggered. |
| 645 | |
| 646 | When an error message is printed for an unhandled exception, the exception's |
| 647 | class name is printed, then a colon and a space, and finally the instance |
| 648 | converted to a string using the built-in function :func:`str`. |
| 649 | |
| 650 | |
| 651 | .. _tut-iterators: |
| 652 | |
| 653 | Iterators |
| 654 | ========= |
| 655 | |
| 656 | By now you have probably noticed that most container objects can be looped over |
| 657 | using a :keyword:`for` statement:: |
| 658 | |
| 659 | for element in [1, 2, 3]: |
| 660 | print element |
| 661 | for element in (1, 2, 3): |
| 662 | print element |
| 663 | for key in {'one':1, 'two':2}: |
| 664 | print key |
| 665 | for char in "123": |
| 666 | print char |
| 667 | for line in open("myfile.txt"): |
| 668 | print line |
| 669 | |
| 670 | This style of access is clear, concise, and convenient. The use of iterators |
| 671 | pervades and unifies Python. Behind the scenes, the :keyword:`for` statement |
| 672 | calls :func:`iter` on the container object. The function returns an iterator |
| 673 | object that defines the method :meth:`next` which accesses elements in the |
| 674 | container one at a time. When there are no more elements, :meth:`next` raises a |
| 675 | :exc:`StopIteration` exception which tells the :keyword:`for` loop to terminate. |
| 676 | This example shows how it all works:: |
| 677 | |
| 678 | >>> s = 'abc' |
| 679 | >>> it = iter(s) |
| 680 | >>> it |
| 681 | <iterator object at 0x00A1DB50> |
| 682 | >>> it.next() |
| 683 | 'a' |
| 684 | >>> it.next() |
| 685 | 'b' |
| 686 | >>> it.next() |
| 687 | 'c' |
| 688 | >>> it.next() |
| 689 | |
| 690 | Traceback (most recent call last): |
| 691 | File "<stdin>", line 1, in ? |
| 692 | it.next() |
| 693 | StopIteration |
| 694 | |
| 695 | Having seen the mechanics behind the iterator protocol, it is easy to add |
| 696 | iterator behavior to your classes. Define a :meth:`__iter__` method which |
| 697 | returns an object with a :meth:`next` method. If the class defines |
| 698 | :meth:`next`, then :meth:`__iter__` can just return ``self``:: |
| 699 | |
| 700 | class Reverse: |
| 701 | "Iterator for looping over a sequence backwards" |
| 702 | def __init__(self, data): |
| 703 | self.data = data |
| 704 | self.index = len(data) |
| 705 | def __iter__(self): |
| 706 | return self |
| 707 | def next(self): |
| 708 | if self.index == 0: |
| 709 | raise StopIteration |
| 710 | self.index = self.index - 1 |
| 711 | return self.data[self.index] |
| 712 | |
| 713 | >>> for char in Reverse('spam'): |
| 714 | ... print char |
| 715 | ... |
| 716 | m |
| 717 | a |
| 718 | p |
| 719 | s |
| 720 | |
| 721 | |
| 722 | .. _tut-generators: |
| 723 | |
| 724 | Generators |
| 725 | ========== |
| 726 | |
Georg Brandl | cf3fb25 | 2007-10-21 10:52:38 +0000 | [diff] [blame] | 727 | :term:`Generator`\s are a simple and powerful tool for creating iterators. They |
| 728 | are written like regular functions but use the :keyword:`yield` statement |
| 729 | whenever they want to return data. Each time :meth:`next` is called, the |
| 730 | generator resumes where it left-off (it remembers all the data values and which |
| 731 | statement was last executed). An example shows that generators can be trivially |
| 732 | easy to create:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 733 | |
| 734 | def reverse(data): |
| 735 | for index in range(len(data)-1, -1, -1): |
| 736 | yield data[index] |
| 737 | |
| 738 | >>> for char in reverse('golf'): |
| 739 | ... print char |
| 740 | ... |
| 741 | f |
| 742 | l |
| 743 | o |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 744 | g |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 745 | |
| 746 | Anything that can be done with generators can also be done with class based |
| 747 | iterators as described in the previous section. What makes generators so |
| 748 | compact is that the :meth:`__iter__` and :meth:`next` methods are created |
| 749 | automatically. |
| 750 | |
| 751 | Another key feature is that the local variables and execution state are |
| 752 | automatically saved between calls. This made the function easier to write and |
| 753 | much more clear than an approach using instance variables like ``self.index`` |
| 754 | and ``self.data``. |
| 755 | |
| 756 | In addition to automatic method creation and saving program state, when |
| 757 | generators terminate, they automatically raise :exc:`StopIteration`. In |
| 758 | combination, these features make it easy to create iterators with no more effort |
| 759 | than writing a regular function. |
| 760 | |
| 761 | |
| 762 | .. _tut-genexps: |
| 763 | |
| 764 | Generator Expressions |
| 765 | ===================== |
| 766 | |
| 767 | Some simple generators can be coded succinctly as expressions using a syntax |
| 768 | similar to list comprehensions but with parentheses instead of brackets. These |
| 769 | expressions are designed for situations where the generator is used right away |
| 770 | by an enclosing function. Generator expressions are more compact but less |
| 771 | versatile than full generator definitions and tend to be more memory friendly |
| 772 | than equivalent list comprehensions. |
| 773 | |
| 774 | Examples:: |
| 775 | |
| 776 | >>> sum(i*i for i in range(10)) # sum of squares |
| 777 | 285 |
| 778 | |
| 779 | >>> xvec = [10, 20, 30] |
| 780 | >>> yvec = [7, 5, 3] |
| 781 | >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product |
| 782 | 260 |
| 783 | |
| 784 | >>> from math import pi, sin |
| 785 | >>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91)) |
| 786 | |
| 787 | >>> unique_words = set(word for line in page for word in line.split()) |
| 788 | |
| 789 | >>> valedictorian = max((student.gpa, student.name) for student in graduates) |
| 790 | |
| 791 | >>> data = 'golf' |
| 792 | >>> list(data[i] for i in range(len(data)-1,-1,-1)) |
| 793 | ['f', 'l', 'o', 'g'] |
| 794 | |
| 795 | |
| 796 | |
| 797 | .. rubric:: Footnotes |
| 798 | |
| 799 | .. [#] Except for one thing. Module objects have a secret read-only attribute called |
| 800 | :attr:`__dict__` which returns the dictionary used to implement the module's |
| 801 | namespace; the name :attr:`__dict__` is an attribute but not a global name. |
| 802 | Obviously, using this violates the abstraction of namespace implementation, and |
| 803 | should be restricted to things like post-mortem debuggers. |
| 804 | |