DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Model, View, Controller HOWTO

01.04.2006
| 15280 views |
  • submit to reddit
        MVC howto
Original vrsion can be found at http://kbrooks.ath.cx/mvchowto/intro.py

#!/usr/bin/python

# MVC Howto - Introduction & code
# What is "MVC"?
#   MVC stands for "Model", "View" & "Controller", a way of seperating your code into
#   manageable and independent chunks that can be changed easily.
# Why use MVC?
#   Because code is independent from each other, it becomes easier for you to change part of the code to do what you want.
#   For example, you could change where data is shown without changing anything else!
# Copyright (c) 2006 Kyle Brooks. Licensed under the Creative Commons Attribution License.
# We will be creating a command line calculator in this HOWTO.
import sys
# Model: a object that interfaces with the real world and returns information.

class Model:
    def calculate(self, left, op, right):
        if op == "+":
            return left + right
        elif op == "-":
            return left - right
# As you see in the code above, the model has the action "calculate".

# View: a object that gets passed the result from the model via the controller. Displays data.
class View:
    def display_data(self, result):
        print result
# As you see in the code above, ALL the view does is display data from the controller.

# Controller: a object that holds a reference to the model and view. Communicates with the model and view. Handles data from the user.
class Controller:
    operands = ["+", "-"]
    def __init__(self, model, view):
        self.model = model
        self.view = view
    def run(self):
        sys.stdout.write(">> ")
        sys.stdout.flush()
        # read a line
        line = sys.stdin.readline()
        line = line.strip()
        if line == "":
            sys.stdout.write("\n>> ")
            sys.stdout.flush()
            return
        for operand in self.operands:
            larray = line.split(operand)
            if larray[0] == line:
                continue
            else:
                break
        else:
            sys.stdout.write("NaN\n")
            sys.stdout.flush()
            return
        larray[0] = int(larray[0])
        larray[2] = int(larray[0])
        result = self.model.calculate(*larray)
        self.view.display_data(result)