Multiple inheritance in Python


The major reasons I switched my population modeling from R to Python is that Python is a nicer language (obligatory xkcd reference here).

Today, I was trying to figure out how multiple inheritance works. Multiple inheritance allows a Python class to inherit the attributes (e.g., functions) from other classes. In my specific context, I am trying to build a complex spatial population model. I want to be able to merge spatial and demographic attributes to create new population classes. However, I was getting tripped up about how to code it in Python.

I found an example on StackOverflow, but I knew I would need to recode it myself to remember. Plus, it’s a physics example, and I like biology story problems better. Here’s the example  I created:

class apples:
def myName(self):
print "apples"

class oranges:
def myName(self):
print “oranges”

class fruit1(apples, oranges):

class fruit2( oranges, apples):

f1 = fruit1()
f2 = fruit2()

Note that if you run the code, each fruit object produces different a different name. This demonstrates the order of multiple inheritance in Python as well as the concept. Also, note how the function myName() is overloaded (which simply demonstrates inheritance).

Test Driven Development


Recently at work, I’ve been building a complex, spatially-explicit population model. The model is complex enough that I started using Python to program it because R did not easily allow me to program the model. Initially while developing the model, I used informal “testing” to make it produced the correct results. For example, I would write a test script to plot simple results and make sure they outputs looked okay. However, this approach was not satisfactory and it was suggested to me that I use Test Drive Development (TDD).

With TDD, I write a small unit test and then program a function or few of lines of code to answer to test. The test is written in a second script file. After writing the new model code, I run the script test file and make sure the test passes. As part of Python’s “Batteries included” philosophy, base Python even comes with a module for unit testing built in.

This seems simple enough, but I now love TDD! With TDD, I know my code does what I think it is doing (something that is not always easy with complicated models or code). Also, I know (can change my code, but not it’s behavior! For example, if I try to improve a function, I now simply re-run the test script to make sure I didn’t change or break anything.

Although seemingly overkill for simple ecological models, TDD improves the quality and reproducibility of our models. Also, using TDD makes me a better and more confident programmer. My only regret is that I did not start using TDD earlier! For anyone wanting to learn TDD, I found this to be a helpful introduction as well as the Python documentation on unit testing.