Object Oriented Programming

We've worked a lot with built-in types:

  • integers
  • strings
  • lists
  • etc.

Some things are too complicated to model using just these basic types, so OOP lets us define our own types, with their own behaviors.

A simple example

Suppose we have a list of geographic coordinates. For each data point, we want to store a city name, latitude, and longitude. We could choose to store them as tuples, like this:

[
(”Los Angeles”, 34.05, -118.25),
(”Denver”, 39.73, -104.98),
(”Seattle”, 47.61, -122.33),
...
]

But, this starts to get less tractable if we want to store more information. What if we want to add elevation, area, average annual temperature, county and state...

(”Seattle”, ”King”, ”WA”, 47.61, -122.33, 520, 71 ... )

Object oriented programming let's us do something like this instead:

>>> seattle = City(”Seattle”)
>>> seattle.county = ”King”
>>> seattle.state = ”WA”
>>> seattle.lat = 47.61
>>>> seattle.lon = -122.33
...
>>> seattle.print_location()
Seattle is in King County, WA at 47.61 N, 122.33 W.

Classes and objects

  • A class is like a blueprint.
  • After defining a class, you can make objects that are instances of that class.
  • seattle = City()City is a class, seattle is an object that is an instance of the City class
  • Objects have members and methods:
    • Members are like variables
    • Methods are like functions.

Using our example above:

>> seattle.lat = 47.61
>> seattle.lon = -122.33

lat and lon are members, like variables

>> seattle.print_location()

print_location is a method, like a function

How to make a new class

We declare classes in much the same way as we declare functions, but with

Constructors

The first method defined should be called __init__. This method is called whenever you make a new object from your class.