A basic model

Models

In an object oriented program, the problem domain for which the program is written is modelled by creating a class representing each concept in that domain.

Here is a simple model for an address book application:

class Address(object):
    def __init__(self, name, email_address):
        self.name = name
        self.email_address = email_address

    def save(self, address_book):
        address_book.add_address(self)
class AddressBook(object):
    def __init__(self):
        self.addresses = []

    def add_address(self, address):
        self.addresses.append(address)

Exercising a model

Whenever you write code that forms part of a model, it is useful to be able to execute that code. The same is true for the examples presented in this tutorial.

The sensible way to execute code is to write some tests for that code. Hence each example here is a test – and to keep things simple we include the toy model and its test together in a single file for now.

To put the simple model presented above through its paces, you can put it together with a test in a file as follows, say test.py:

from __future__ import unicode_literals
from __future__ import print_function
from nose.tools import istest

class Address(object):
    def __init__(self, name, email_address):
        self.name = name
        self.email_address = email_address

    def save(self, address_book):
        address_book.add_address(self)


class AddressBook(object):
    def __init__(self):
        self.addresses = []

    def add_address(self, address):
        self.addresses.append(address)




@istest
def test_model():
    contacts = AddressBook()
    Address('John', '[email protected]').save(contacts)
    Address('Jane', '[email protected]').save(contacts)

    assert contacts.addresses[0].name == 'John'
    assert contacts.addresses[0].email_address == '[email protected]'

    #import pdb; pdb.set_trace()
    assert contacts.addresses[1].name == 'Jane'
    assert contacts.addresses[1].email_address == '[email protected]'

You can execute this example by running:

nosetests test.py

Sometimes it is useful to include a line somewhere in that test which will invoke the Python debugger so that you can play around with the running code:

import pdb; pdb.set_trace()

...but then be sure to invoke nosetests with its -s commandline option:

nosetests -s test.py

Table Of Contents

Previous topic

An application that actually does something

Next topic

A persistent model