Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lesson 2 - Object Oriented Programming

Lesson 2 - Object Oriented Programming

Avatar for Dana Spiegel

Dana Spiegel

October 15, 2012
Tweet

More Decks by Dana Spiegel

Other Decks in Technology

Transcript

  1. Quick Review • Python syntax • Readable code • Object

    oriented, dynamically typed, imperative • Types • String, Numeric, Date Boolean, Collection, None • Control Flow • Conditionals • Iteration • Methods and modules • def, parameters • Files, directories • Get Python working on your laptop (required for tonight’s homework) 2
  2. Python: Objects • Everything in Python is an object •

    Objects have both data and actions • data is contained in “properties” or “slots” • actions are defined in “methods” • The string 'John Doe' is an object in Python • The value 'John Doe' is contained in a default property • The methods are inherited by its definition as a type of str, for example upper, replace, and index 3 s = 'John Doe' typeof(s) => str # s is an object of type str print s => 'John Doe' # s contains the data 'John Doe' s.upper() => 'JOHN DOE' s.replace('John', 'Jane') => 'Jane Doe' s.index('D') => 5
  3. Python: Classes • Object oriented programming is about defining classes,

    which are prototypes for objects • Classes are important because custom objects are created by instantiating classes • When you create a list, python instantiates an object of type list • Class definitions provide methods and properties (slots) that will be created in the instantiated object: 4 l = [1, 2, 3, ] typeof(l) => list class Game(object): team1 = None team2 = None def __init__(self, team1, team2): self.team1 = team1 self.team2 = team2
  4. Python: Classes (cont.) • Classes are instantiated by calling them

    (sometimes with arguments) like methods: • Methods and properties defined in the class exist in the instantiated object • self a special way that python allows an object to refer to itself (similar to this in Java and JavaScript • Methods defined in a Class must declare self as their first argument, but you don’t pass it in when you call them (this happens automatically) 5 >>> Game() TypeError: __init__() takes exactly 3 arguments (1 given) >>> game = Game('Team A', 'Team B') >>> game <__main__.Game at 0x10f1de910> >>> print game.team1 Team A
  5. Example: Game Class 6 class Game(object): team1 = None team2

    = None def __init__(self, team1, team2): self.team1 = team1 self.team2 = team2 self.innings = [] def current_score(self): return (sum([s[0] for s in self.innings]), sum([s[1] for s in self.innings]), ) >>> game = Game('foo','bar') >>> game.innings.append((1, 0)) >>> game.innings.append((0, 1)) >>> game.innings.append((2, 0)) >>> game.current_score() (3, 1)
  6. Modeling Classes 7 • Object oriented design can be hard!

    • Good OO modeling requires thinking about the logical structure of how things are organized • In class exercise: • Model a parking lot • Model a multi-level parking structure • Model a baseball game • Model a baseball team
  7. • test.py: • Run: python test.py • Run on Unix/Mac

    OS X/Linux: ./test.py Write a stand-alone python program 8 #!/usr/bin/env python def test_python(s): print s if __name__ == '__main__': test_python('test')
  8. Documentation • Good code is self documenting, but even then,

    it should have comments • Document each method your write, and intersperse comments describing why you are doing something • Clearly define what inputs you expect and what outputs you will provide • You will be reading and revising your own code, and after 6 months you won’t remember what you did and why! 9 def __resize__(self): """ Resizes the array by creating doubling the storage_length, creating a new list and re-hashing all stored items """ new_storage_length = self.storage_length * 2 # initialize a new list and pre-fill it with empty lists new_items = [[] for i in range(new_storage_length)] for item_list in self.items: ....
  9. Testing • There are only 2 ways to know that

    your code does what you believe it does: • Write unit tests • Pray • Writing units tests is the only way to “guarantee” that your code does what it is supposed to do • Unit tests are a form of software testing that validates code logic • They aren’t the only type of testing you need to do! • Unit tests are best at testing the outputs of a method for a variety of inputs • They must be thorough! 10
  10. Example: Unit Tests 11 import unittest class TestHashMap(unittest.TestCase): def test_init(self):

    h = HashMap() self.assertEqual(0.75, h.load) self.assertEqual(64, h.storage_length) self.assertEqual(0, h.item_count) self.assertEqual([[] for i in range(64)], h.items) def test_index_for_key(self): h = HashMap() self.assertEqual(h.__index_for_key__('abc', l=10), 1) self.assertEqual(h.__index_for_key__('bcd', l=10), 2) self.assertEqual(h.__index_for_key__('abc'), 35) self.assertEqual(h.__index_for_key__('bcd'), 40) h.storage_length = 100 self.assertEqual(h.__index_for_key__('abc'), 11) self.assertEqual(h.__index_for_key__('bcd'), 72) 1. https://gist.github.com/eb681f836648cac4fd3b
  11. Good methodology • Spend time before writing code to ensure

    complete understanding of problem and solution • Write code that anyone can understand • Keep methods as short as possible (easier to test) • Refactor on a regular basis • Use variable names that are descriptive! • Test your code, even against unlikely circumstances • Read other people’s code as much as possible • This is the only way to become a good developer • Read about developing software • Challenge yourself • This is the only way to become a good developer • Most important: Have fun! 12
  12. In Class: Start Working with Python • Work with Python!

    • Use python shell to call methods and assign variables • Import datetime and instantiate a datetime object • Use datetime instance methods • Write python code in a module and run it • Homework: • Write a Python method that: • Takes a list as its argument • Removes all negative and 0 value elements • Returns the list • Method should have comments (like all good code!) • Email me the method definition 13