{ "metadata": { "name": "oop" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Object Oriented Programming\n", "===========================\n", "\n", "We've worked a lot with built-in types:\n", "\n", "* integers\n", "* strings\n", "* lists\n", "* etc.\n", "\n", "Some things are too complicated to model using just these basic types, so OOP lets us define our own types, with their own behaviors." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A simple example\n", "----------------\n", "\n", "Suppose we have a list of geographic\n", "coordinates. For each data point, we want to\n", "store a city name, latitude, and longitude.\n", "We could choose to store them as tuples, like\n", "this:\n", "\n", " [\n", " (\u201dLos Angeles\u201d, 34.05, -118.25),\n", " (\u201dDenver\u201d, 39.73, -104.98),\n", " (\u201dSeattle\u201d, 47.61, -122.33),\n", " ...\n", " ]\n", "\n", "But, this starts to get less tractable if we want to\n", "store more information. What if we want to add\n", "elevation, area, average annual temperature,\n", "county and state...\n", "\n", " (\u201dSeattle\u201d, \u201dKing\u201d, \u201dWA\u201d, 47.61, -122.33, 520, 71 ... )\n", "\n", "Object oriented programming let's us do something like this instead:\n", "\n", " >>> seattle = City(\u201dSeattle\u201d)\n", " >>> seattle.county = \u201dKing\u201d\n", " >>> seattle.state = \u201dWA\u201d\n", " >>> seattle.lat = 47.61\n", " >>>> seattle.lon = -122.33\n", " ...\n", " >>> seattle.print_location()\n", " Seattle is in King County, WA at 47.61 N, 122.33 W.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Classes and objects\n", "-------------------\n", "* A class is like a blueprint.\n", "* After defining a class, you can make objects that are instances of that class.\n", "* ``seattle = City()`` \u2190 ``City`` is a class, ``seattle`` is an object that is an\n", "instance of the ``City`` class\n", "* Objects have members and methods:\n", " * Members are like variables\n", " * Methods are like functions.\n", "\n", "Using our example above:\n", "\n", " >> seattle.lat = 47.61\n", " >> seattle.lon = -122.33\n", "\n", "lat and lon are members, like variables\n", "\n", " >> seattle.print_location()\n", "\n", "print_location is a method, like a function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "How to make a new class\n", "-----------------------\n", "\n", "We declare classes in much the same way as we declare functions,\n", "but with " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Constructors\n", "------------\n", "\n", "The first method defined should be called ``__init__``.\n", "This method is called whenever you make a new object from your class." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }