In the first OOP unit you learned the basic semantics of OOP in python. This week we will attempt to provide concrete examples of the use of objects in python (and other OOP languages) and provide arguments in favor and against the use of OOP in python.
OOP is a tool that, when used wisely, can help you to structure your programs in a way which might be more readable, easier to maintain and more flexible than purely procedural programs. But why is that so? In this class we will provide examples for five core concepts of OOP:
Data abstraction refers to the separation between the abstract properties of an object and its internal representation. By giving a name to things and hiding unnecessary details from the user, objects provide an intuitive interface to concepts which might be extremely complex internally.
Going back to our examples from last week: we used the term "objects" in programming as surrogate for actual "objects" in the real world: a cat, a pen, a car... These objects have a "state" (in OOP: attributes) and realize actions (in OOP: methods). For a pen, the attributes could be: the color of the ink, the volume of remaining ink, the size of the point, etc. The actions (methods) could be: write(), fill_ink(), etc.
Leaving the real world and entering the programming world: if a concept in your program is easily describable in terms of "state" and "actions", it might be a good candidate for writing a class.
Taking a widely used object in Python: an instance of the class string:
a = 'hello!'
The "state" of our object is relatively simple to describe: it is the sentence (list of characters) stored in the object. We have access to this state (we can print its values) but the way these values are stored in memory is abstracted away. We don't care about the details, we just want a string. Now, a string provides many actions:
a.capitalize()
a.capitalize().istitle()
a.split('l')
Abstractions should be as simple and well defined as possible. Sometimes there is more than one possible way to provide an abstraction to the user, and it becomes a debate among the programmers of a project whether these abstractions are useful or not.
Well defined abstractions can be composed together. A good example is provided by the xarray library: an xarray.DataSet
is composed of several xarray.DataArray
objects. These xarray.DataArray
objects have the function to store data (a numpy.ndarray
object) together with coordinates (other numpy.ndarray
objects) and attributes (units, name, etc.). This chain of abstractions is possible only if each of these concepts has a clearly defined role: xarray does not mess around with numbers in arrays: numpy does. Inversely, numpy does not care whether an array has coordinates or not: xarray does.
Encapsulation is tied to the concepts of abstraction. By hiding the internal implementation of a class behind a defined interface, users of the class do not need to know details about the internals of the class to use it. The implementation of the class can be changed (or internal data can be modified) without having to change the code of the users of the class.
In python, encapsulation is more difficult than in other languages like Java. Indeed, Java implements the concept of private methods and attributes, which are hidden from the user per definition. In python, nothing is hidden from the user: however, developers make use of conventions to inform the users that a method or attribute is not meant to be used by the class alone, not by users. Let's take an xarray DataArray as an example:
import xarray as xr
import numpy as np
da = xr.DataArray([1, 2, 3])
np.array(dir(da)) # we use np.array to prevent lengthy print
In this long list of methods and attributes, some of them are available and documented. For example:
da.values
Other methods/attributes start with one underscore. This underscore has no special meaning in the Python language other than a warning to the users: "if you use this method/attribute, do it at your own risk". For example:
da._in_memory
_in_memory
is an attribute which is meant for internal use in the class (it is called private). Setting it to another value might have unpredictable consequences, and relying on it for your own code is not recommended: the xarray developers might rename it or change it without notice.
The methods having two trailing and leading underscores have a special meaning in Python and are part of the language specifications. We already encountered __init__
for our class instantiation, and we will talk about the others later in this chapter.
Modularity is a technique to separate different portions of the program (modules) based on some logical boundary. Modularity is a general principle in programming, although object-oriented programming typically makes it more explicit. Taking the example of xarray.DataArray
and numpy.Array
: both classes have very clear domains of functionality. The latter shines at doing fast numerical computations on arrays, the former provides an intuitive abstraction to the internal arrays by giving names and coordinates to its axes.
Polymorphism represents the technique of creating multiple classes that obey the same interface. Objects from these classes can then be mixed at runtime. In other words, polymorphism originates from the fact that a certain action can have well defined but different meanings depending on the objects they apply to.
An example of polymorphism is provided by the addition in python:
1 + 1
1 + 1.2
[1, 2] + [3, 4]
np.array([1, 2]) + [3, 4]
Each of these addition operations are performing a different action depending on the object they are applied to. OOP relies on polymorphism to provide higher levels of abstraction. In our Cat
and Dog
example from last week, both classes provided a say_name()
method: the internal implementation, however, was different in each case.
Many OOP languages (including Python) provide powerful tools for the purpose of polymorphism. One of them is operator overloading:
class ArrayList(list):
def __add__(self, other):
"""Don't do this at home!"""
return [a + b for a, b in zip(self, other)]
What did we just do? The class definition (class ArrayList(list)
) indicates that we created a subclass of the parent class list
, a well known data type in python. Our child class has all the attributes and methods of the original parent class:
a = ArrayList([1, 2, 3])
len(a)
Now, we defined a method __add__
, which allows us to do some python magic: __add__
is the method which is actually called when two objects are added together. This means that the two statements below are totally equivalent:
[1] + [2]
[1].__add__([2])
Now, what does that mean for the addition on our ArrayList
class? Let's try and find out:
a + [11, 12, 13]
We just defined a new way to realize additions on lists! This is a very powerful mechanism, but comes with great responsibility: it should be used with caution and only for very clear use cases. A prominent example is provided by numpy: by implementing the __add__
method on ndarray objects, they provide a new functionality which is hidden from the user but intuitive at the same time, avoiding bad surprises.
TODO: describe examples from OGGM mass-balance model, duck-typing.
TODO
Back to the table of contents, or jump to the pelita project!