We've worked a lot with built-in types:
Some things are too complicated to model using just these basic types, so OOP lets us define our own types, with their own behaviors.
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.
seattle = City()←
Cityis a class,
seattleis an object that is an instance of the
Using our example above:
>> seattle.lat = 47.61 >> seattle.lon = -122.33
lat and lon are members, like variables
print_location is a method, like a function