LPTHW Exercises 40-44
(12/9/2013 -- 6:30PM PST)
Object Oriented Programming
Review
- Name all known Python data types
- What does mutability mean?
- Accessing items
- 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 = teamsself.score = 0def score_basket(self):self.score += 2def print_score(self):print self.score
Exercise 40: Continued
Classes are similar in purpose and mechanics to modules
- Makes code reusable
- Preserves state (unlike functions)
- 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 = namedef print_name(self): print self.nametom = Human("Tom")loraine = Human("Loraine")tom.age = 30print 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 = 80def __init__(self, name):self.name = nametom = 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 complicateddef even_a_func_is_an_object():print Trueeven_a_func_is_an_object.really = True
exercise 41: Terminology
- class
- object (two meanings)
- instance
- def
- self
- inheritance
- composition
- attribute
- is-a
- has-a
Exercise 42: Intro to Inheritance
class Animal(object):def __init__(self, name):self.name = nameclass Fish(Animal): def __init__(self, name, habitat): super(Fish, self).__init__(name) self.habitat = habitatclass Salmon(Fish): def swim():print "upstream"class Halibut(Fish): def communicate():print "yarp" class GeneticHybridFish(Salmon, Halibut): passfish = GeneticHybridFish("Roy", "Brazil")
Review: problem sets to cover the entire course
By benjaminplesser
Review: problem sets to cover the entire course
- 1,028