Object-Oriented Programming

Combining Data and Behavior

What are some common properties of cars?

  • color
  • wheels
  • seats
  • steering wheel
  • engine
  • doors
  • accelerator
  • brake

What are some actions you can perform?

  • open door
  • start engine
  • turn left/right
  • accelerate
  • stop
  • turn off engine
  • turn on cruise control

Overview

  • Definitions
  • Defining Classes
  • Using Instances

What is OOP?

  • Nothing magical, just a different style
  • Procedural (like a recipe)
  • Functional (more mathematical)
  • Many languages like Python combine these styles.
  • OOP encapsulates data and behavior into objects
  • Objects have interfaces that allow them to interact
  • OOP tries to map programming to how we think about the world.

Classes vs. instances

  • Objects in OOP are members of classes
  • Features shared by members are mapped in a class definition
  • Individual instances have their own attributes and state

You have already been using objects

  • All data types (for example, string, list, dictionary) are objects
>>> s = 'Hello World'
>>> type(s)
<class 'str'>
>>> l = list()
>>> type(l)
<class 'list'>
>>> dir(l)
['__add__', '__class__', ...]

In fact, in Python almost everything is an object

  • Objects have shared behaviors defined by their classes
  • At the same time, individual instances have different content
  • Much of the complexity is “hidden” inside the objects

Defining your own class

  • Define a class with the “class” keyword
  • Define methods inside the class with indented “def” blocks
class Pet():
    def __init__(self, name):
        self.name = name

Initializers

  • The __init__() method is an initializer
  • The double underscore (dunderscore) indicates that __init__ has a special purpose
  • It is called automatically when a new instance is created
  • Often __init__() is used to set up attributes (here to give each pet a name)

Attributes and methods

  • Attributes are properties specific to the instance
  • Methods are like functions defining behaviors specific to the members of a class
class Pet():
    def __init__(self, name):
        self.name = name
    def eat(self):
        print('Nom nom nom')

Interacting with an object

class Pet():
    def __init__(self, name):
        self.name = name
    def eat(self, food):
        print(f'Nom nom. {self.name} likes {food}.')

>>> mypet = Pet('Spot')
>>> mypet.eat('dogfood')
Nom nom. Spot likes dogfood.

Dot notation

  • Notice in the previous example how eat() was called
  • Notice as well how the attribute “.name” was accessed
  • This is called dot notation
    • used to access attributes of the instance
    • used to apply methods to the instance
    • “self” in the class definition means particular to the instance

In summary

  • Combining Data and Behavior
  • Defining Classes
  • Attributes and Methods
  • Interacting with Instances
  • Exercise