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