OOP terminology

Object-oriented programming (OOP) is a style of programming that allows you to think of code in terms of "objects." Here's an example of a Car class:

class Car(object):

  num_wheels = 4
  gas = 30
  headlights = 2
  size = 'Tiny'

  def __init__(self, make, model):
      self.make = make
      self.model = model
      self.color = 'No color yet. You need to paint me.'
      self.wheels = Car.num_wheels
      self.gas = Car.gas

  def paint(self, color):
      self.color = color
      return self.make + ' ' + self.model + ' is now ' + color

  def drive(self):
      if self.wheels < Car.num_wheels or self.gas <= 0:
          return 'Cannot drive!'
      self.gas -= 10
      return self.make + ' ' + self.model + ' goes vroom!'

  def pop_tire(self):
      if self.wheels > 0:
          self.wheels -= 1

  def fill_gas(self):
      self.gas += 20
      return 'Gas level: ' + str(self.gas)

Here's some terminology:

  • class: a blueprint for how to build a certain type of object. The Car class (shown above) describes the behavior and data that all Car objects have.
  • instance: a particular occurrence of a class. In Python, we create instances of a class like this:

    >>> my_car = Car('Tesla', 'Model S')

    my_car is an instance of the Car class.

  • attribute or field: a variable that belongs to the class. Think of an attribute as a quality of the object: cars have wheels and size, so we have given our Car class self.wheels and self.size attributes. We can access attributes using dot notation:

    >>> my_car.size
    'Tiny'
    >>> my_car.wheels
    4
  • method: Methods are just like normal functions, except that they are tied to an instance or a class. Think of a method as a "verb" of the class: cars can drive and also pop their tires, so we have given our Car class the methods drive and pop_tire. We call methods using dot notation:

    >>> my_car = Car('Tesla', 'Model S')
    >>> my_car.drive()
    'Tesla Model S goes vroom!'
  • constructor: As with data abstraction, constructors describe how to build an instance of the class. Most classes have a constructor. In Python, the constructor of the class defined as __init__. For example, here is the Car class's constructor:

    def __init__(self, make, model):
            self.make = make
            self.model = model
            self.color = 'No color yet. You need to paint me.'
            self.wheels = Car.num_wheels
            self.gas = Car.gas

    The constructor takes in two arguments, make and model. As you can see, the constructor also creates the self.color, self.wheels and self.gas attributes.

  • self: in Python, self is the first parameter for many methods (in this class, we will only use methods whose first parameter is self). When a method is called, self is bound to an instance of the class. For example:

    >>> my_car = Car('Tesla', 'Model S')
    >>> my_car.drive()

    Notice that the drive method takes in self as an argument, but it looks like we didn't pass one in! This is because the dot notation implicitly passes in car as self for us.

Car WWPD

Question 1: Car

Use OK to test your knowledge with the following What would Python print questions:

python3 ok -q car -u

If you get stuck try typing these in the interpreter yourself

python3 -i

Keyboard

Question 2: Keyboard

We'd like to create a Keyboard class that takes in an arbitrary number of Buttons and stores these Buttons in a dictionary. The keys in the dictionary will be strings that represent the position on the Keyboard, and the values will be the respective Button. Fill out the methods in the Keyboard class according to each description, using the doctests as a reference for the behavior of a Keyboard.

class Keyboard:
    """A Keyboard takes in a list of buttons, and has a
    dictionary of positions as keys, and Buttons as values.

    >>> b1 = Button("button1", "H")
    >>> b2 = Button("button2", "I")
    >>> k = Keyboard([b1, b2])
    >>> "button1" in k.buttons.keys() # Make sure to add the button to dictionary
    True
    >>> k.buttons["button1"].letter
    'H'
    >>> k.buttons["button1"].name
    'button1'
    >>> k.press("button1")
    'H'
    >>> k.press("button100")
    ''
    >>> b1.pressed
    1
    >>> b2.pressed
    0
    >>> k.typing(["button1", "button2"])
    'HI'
    >>> k.typing(["button2", "button1"])
    'IH'
    >>> b1.pressed # make sure typing calls press!
    3
    >>> b2.pressed
    2
    """

    def __init__(self, buttons):
        self.buttons = {}
"*** YOUR CODE HERE ***"
for button in buttons: self.buttons[button.name] = button
def press(self, name): """Takes in a name of the button pressed, and returns that button's letter. Return an empty string if the button does not exist. You can access the keys of a dictionary d with d.keys(). """
"*** YOUR CODE HERE ***"
if name in self.buttons.keys(): b = self.buttons[name] b.pressed += 1 return b.letter return ''
def typing(self, typing_input): """Takes in a list of names of buttons to be pressed, and returns the total output. Make sure to call self.press"""
"*** YOUR CODE HERE ***"
accumulate = '' for name in typing_input: accumulate+=self.press(name) return accumulate
class Button: def __init__(self, name, letter): self.name = name self.letter = letter self.pressed = 0

Use OK to test your code:

python3 ok -q Keyboard

Submit

Make sure to submit this assignment by running:

python3 ok --submit