LPTHW Exercises 40-44 


(12/9/2013 -- 6:30PM PST)




Object Oriented Programming

Review


  1. Name all known Python data types
  2. What does mutability mean?
  3. Accessing items
  4. Built-in functions in advanced data types

Exercise 40: Introduction to classes


Complex data type (structure) 
 allows us to model the real world
How would we represent a basketball game in a program?
 class BasketballGame(object):    def __init__(self, teams):        self.teams = teams        self.score = 0        def score_basket(self):        self.score += 2      def print_score(self):        print self.score    

Exercise 40: Continued


Classes are similar in purpose and mechanics to modules
  1. Makes code reusable
  2. Preserves state (unlike functions)
  3. Attributes accessed through dot notation  


Unlike modules, which are imported only once,
 classes can be used to create a nearly infinite number of (largely) independent versions of themselves (objects)

Exercise 40: Continued (Objects)


A class is a blueprint  which defines all  attributes.
We use that blueprint to create objects, which are (largely) independent instances of the class
 class Human(object):                  def __init__(self, name):                            self.name = name                            def print_name(self):
             print self.name        tom = Human("Tom")
loraine = Human("Loraine")
tom.age = 30
print tom.age, loraine.age

EXTRA CONTENT: CLASS PROPERTIES


We said previously that objects are largely independent.
It is possible to share state within a Class.

 class Human(object):    expected_lifetime = 80       def __init__(self, name):       self.name = name
tom = Human("Tom")loraine = Human("Loraine")print tom.expected_lifetime, loraine.expected_lifetime

extra content: objects everywhere


Everything in Python is an object

 "strings are objects with properties and methods" ["lists are objects"] {"as_are": "dictionaries"} 5   ### same with integers, floats, and Booleans -- they're more complicated
def even_a_func_is_an_object(): print True even_a_func_is_an_object.really = True

exercise 41: Terminology


  1. class
  2. object (two meanings)
  3. instance
  4. def
  5. self
  6. inheritance
  7. composition
  8. attribute
  9. is-a
  10. has-a

Exercise 42: Intro to Inheritance

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

class Fish(Animal):
    def __init__(self, name, habitat):
        super(Fish, self).__init__(name)
        self.habitat = habitat


class Salmon(Fish): def swim(): print "upstream"
class Halibut(Fish): def communicate(): print "yarp" class GeneticHybridFish(Salmon, Halibut): pass
fish = GeneticHybridFish("Roy", "Brazil")

Review: problem sets to cover the entire course

By benjaminplesser

Review: problem sets to cover the entire course

  • 1,008