03 Introduction to Python IV — Modules and Objects
30 Jan 2018We are continuing from
the previous lesson in the "work directory"
~/PHY494/03_python
. We will use ipython
and your text editor.
Re-using code is key to writing maintainable and correct code. We already learnt how to package code into functions. Now we learn how to package functions into modules.
We will also briefly talk about objects because everything in Python is an "object". Objects are a more general approach to "packaging code into re-usable units".
Modules
Modules (and packages) are "libraries" for Python code.
Create a file constants.py
:
Importing modules
We can import the file in the python interpreter with the
import
statement (note: constants.py
must be in the same directory, check
with %pwd
and %ls
)
Contents of a module are accessed with the "dot" operator, e.g,
constants.pi
.
Other ways to import:
Activity: Import and use your myfuncs
module
In the previous lesson you created myfuncs.py, which contains three different functions. Now treat it as a module and import it and use the functions in the module.
You should be able to do use your functions in the following manner
and get output
1.0
100.0
Standard Library and the Python Eco System
The Python Standard Library contains many useful packages/modules. They are always available. For example
Other packages that we are going to use
Objects
Using functions is the most important way to write scientific code. The basic approach is to have blocks of code that take in data and return results; this is called procedural programming. But there is also another way in which data and functions are combined into something called an object, which leads to object oriented programming (OOP). An object contains data (held in variables that are called attributes) and it also contains functions (called methods) that know how to operate on the data in the object.
Python is an object oriented (OO) language and objects are everywhere — in fact everything is an object in Python.
Some Python objects
Even if you don't use object-oriented programming, you still need to know how to work with Python objects. We look at a few examples.
Each built-in type
(int
, float
, str
, …) is an object with associated methods
and attributes.
Strings
The text sequence — or "string" — type
str
has lots of string
methods:1
Note that the string object itself contains all these methods:
The output of many of these methods is again a string so one can easily concatenate or "chain" methods:
If you are curious about other methods of an object such as the string
sentences
, use the TAB
-completion in ipython
on the object with
a following period .
:
This will show you all methods and attributes.
Lists
The list
type contains a large number of useful
methods
that allow one to manipulate the list. Typically, all operations are
done "in place", i.e., they change the list itself.
Creating objects: classes (advanced topic)
In Python one creates an object by first defining a class:2
and then instantiating the object (creating an instance of the class)
Notes on the class definition above:
__init__()
is a special method that is called when the class is instantiated: it is used to populate the object with user-defined values.- The first argument of each method
(including
__init__()
) is always calledself
and refers to the class itself. - So-called instance attributes are created with
self.ATTRIBUTE_NAME
, e.g.,self.pos
. - Methods are defined just like ordinary
Python functions except that the first argument is
self
.
In this example we created an object named ball
, which is of type
Sphere
:
Attributes and Methods
Objects contain attributes (variables that are associated with the
object) and methods (functions that are associated with the
object). Attributes and methods are accessed with the "dot"
operator. (Within the class definition, attributes and methods are
also accessed with the dot-operator but the class itself is referred
to as self
— this is just the first argument in each method and
you should always, always name it "self".)
In the example, pos
and radius
are
attributes, and can be accessed as ball.pos
and ball.radius
. For
instance, the Sphere
object named ball
has position
because we provided the pos
argument (0, 0, 10)
on
instantiation. Similarly, we created a ball with radius 2.
One can assign to these attributes as usual, e.g., directly change the position
The Sphere.volume()
method computes the volume of the sphere:
The Sphere.translate()
method changes the position of the object by
adding a translation vector t
to Sphere.pos
:
Note that this method did not return any values but it changed the
data in Sphere.pos
.
Independence of instances
Each instance of a class is independent from the other instances. For
example, ball
and a new balloon
can be moved independently
even though we start them at the same position:
Inheritance
New classes can be built on existing classes in such a way that the new class contains the functionality of the existing class. This is called inheritance and is a very powerful way to organize large code bases.
Only a small example is given to illustrate the basic idea: We use our
Sphere
class to create planets. A planet is (almost) a sphere but it
also has a name and a mass: The new Planet
class inherits from
Sphere
by supplying Sphere
as an argument to Planet
:
gives 5513 kg/m3 because the Planet
class inherited the
volume()
method from Sphere
.
Final comments on objects
For most of the class you will not need to work with classes, i.e.,
you do not have to design your programs in an object-oriented
manner. However, everything is an object and we will constantly create
objects and work with their methods and attributes. For example
list.append()
is a method of a list
object. Even modules are
objects and therefore you are using the dot operator to access its
contents.
Tip: In ipython
you can list all the attributes and methods of
an object by typing the object's name, a dot, and then hitting the TAB
key twice. TAB-completion together with the question mark (help)
operator is how most programmers quickly learn about Python classes
and objects.
Footnotes
-
Do not type the standard Python prompt
>>>
, it is just shown to distinguish input from output. ↩ -
It is convenient to put the class definition into a separate module, let's say
bodies.py
, and then you can import the class definitions asfrom bodies import Sphere
This tends to be more manageable than working interactively and it is an excellent way to modularize code. ↩