
P1: JYS
app01 JWBK378-Fletcher May 1, 2009 19:56 Printer: Yet to come
Appendix A: Python 203
Unlike C++ with its notion of private, protected and public access mechanisms,
everything in a class is publicly accessible and due to Python’s dynamic nature the definition
of a class can even be changed during execution of the script(!):
>>> def salary(mgr):
... return mgr.salary
...
>>> print salary(m)
20000
>>> manager.earns = salary
>>> print m.earns()
20000
>>>
Programming with classes is ubiquitous in Python and this section just covers the basics.
The newcomer to Python is recommended to take the time to become more familiar with them
early on.
A.2.6 Modules and Packages
A module is a lexical unit of Python code stored in a file on disk. Let us suppose the existence
of a file ‘complex.py’ with contents something like the following:
class complex(object):
def
init (self, re, im):
self.re, self.im = (re, im)
def real
part(self):
return self.re
def imag
part(self):
return self.im
def
str (self):
return "%f + %fi" % (self.re, self.im)
def
add (self, other):
return complex(self.re + other.re, self.im + other.im)
# ...
def conjugate(x):
return complex(x.real
part(), -x.imag part())
# ...
We can use the Python import directive to bring all of the type declarations and function
definitions defined in ‘complex.py’ into the current scope like this:
>>> from complex import *
>>> i = complex(0, 1)