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