1 of 39

OOP in Python

July 31st, 2018

Computing in the News

Facebook announces it will shut off user data access for hundreds of thousands of apps until they show they are compliant with new data privacy regulations.

https://www.theverge.com/2018/7/31/17637244/facebook-apps-api-access-shut-off-missed-review-deadline

2 of 39

Announcements

  • Final Project Milestone due tonight, 7/31
    • It’s 5 points, really short questions, do it
  • Social Implications Assignment #2 due Friday, 8/3
    • You get to make your own prompt!
  • Final Project Party on Friday, 8/3 from 2-4 PM
    • 310 Soda
  • Final Review Session on Sunday, 8/5 from 6:30-8:30 PM
    • 521 Cory (across the street)
    • Slides will be posted after the session
  • Start practicing for the final exam! Samples are on the course website

3 of 39

Today’s Lecture: An Overview

  • A Review of OOP
  • OOP in Python
  • Classes and Inheritance

  • There’s going to be a lot of content on these slides - ask questions if you need to

4 of 39

OOP: A Review

  • Objects are collections of data.

  • Objects have attributes, which are variables or characteristics.

  • Objects also have methods, which are functions.

  • Each object has a local state, which includes the object’s attributes and methods. The local state is not accessible by other objects.

  • Objects communicate via message-passing.

5 of 39

Intuition

Class: Sprites

  • All sprites start out at 100% size
  • All sprites have a name and a color specific to that sprite
  • All sprites have a “Say” method

Instance: Alonzo sprite

  • This sprite starts out at 100% size
  • But it has an antenna, a unique name (“Alonzo”), and color (“yellow”)
  • Alonzo always says “CS10 WOO!”

6 of 39

Classes in Python

7 of 39

Classes and Instances

  • A class is category of objects.

  • An instance is a single example or manifestation of a class.

  • To create an instance of a class, we use a constructor method.�
  • Classes contain methods, which are procedures/functions that only that class or instances of that class can access

8 of 39

Classes and Instances

class Sprite:

size = ‘100’

def __init__(self, name,

color):

self.name = name

self.color = color

def say(self, text):

print(text)

Can you name each of the elements (class statement, constructor, and class method) in this code?

9 of 39

Classes and Instances

class Sprite:

size = ‘100’

def __init__(self, name,

color):

self.name = name

self.color = color

def say(self, text):

print(text)

Class Declaration

Object Constructor

Class Method

10 of 39

Class vs. Instance Attributes and Methods

  • There are class attributes and methods, which are shared by all instances of the class

  • But there are also instance attributes and methods, which are unique to particular instances of the class

  • Like in Snap!, in Python, instance attributes and methods of the same name hold precedence over class attributes and methods.

11 of 39

Classes and Instances

class Sprite:

size = ‘100’

def __init__(self, name,

color):

self.name = name

self.color = color

def say(self, text):

print(text)

Which attributes are class attributes and which attributes are instance attributes?

12 of 39

Classes and Instances

class Sprite:

size = ‘100’

def __init__(self, name,

color):

self.name = name

self.color = color

def say(self, text):

print(text)

Class Attribute

Instance Attribute

13 of 39

Instantiating an Instance

  • To create an instance of a class, you must call the constructor

  • We use dot notation!

  • Now our Alonzo variable points to a Sprite object that has the name ‘Alonzo’ and the color ‘yellow’
    • Note these are all the inputs we passed into the constructor!

Alonzo = Sprite.init(‘Alonzo’, ‘yellow’)

14 of 39

Accessing Object Data

  • Now that we have our Alonzo object, how do we access its attributes and methods?
    • Dot notation again!

>>> Alonzo.color

‘Alonzo’

>>> Alonzo.size

‘100’

>>> Alonzo.say(“CS10 WOO!”)

‘CS10 WOO!’

15 of 39

Mutating Your Objects

  • Remember that objects are mutable! You can change attributes in your objects�
  • Reassign attributes the way you would assign variables�

>>> NewSprite = Sprite.init(‘Alonzo’, ‘green’)

>>> NewSprite.color

>>> “green”

>>> NewSprite.color = “purple”

>>> NewSprite.color

>>> “purple”

16 of 39

Mutating Your Objects

  • Changing an instance attribute only changes the attribute for that instance

  • But changing a class attribute changes the attribute for all objects that haven’t been changed�

>>> Alonzo.size = ‘1000000’

>>> NewSprite.size

‘100’

>>> Sprite.size = ‘1000’

>>> NewSprite.size

‘1000’

>>> Alonzo.size

‘1000000’

17 of 39

Check Your Understanding

If we didn’t change Alonzo’s size attribute first, what would Alonzo’s size be after we changed the Sprite class’s size attribute?

  1. ‘100’
  2. ‘1000’
  3. ‘1000000’

18 of 39

Check Your Understanding

If we didn’t change Alonzo’s size attribute first, what would Alonzo’s size be after we changed the Sprite class’s size attribute?

  • ‘100’
  • ‘1000’
  • ‘1000000’

When we mutated the Alonzo object, we gave Python a local value to go to instead of a class value

19 of 39

What happened to the self?

class Sprite:

size = ‘100’

def __init__(self, name,

color):

name = name

color = color

def say(self, text):

print(text)

What happened to the self input?

20 of 39

Bound Methods

  • Functions and procedures defined in a class are bound methods�
  • These automatically pass the object in as the first input
    • So the ‘self’ input doesn’t actually go away!

  • When you call this:

  • You’re actually calling this:

>>> NewSprite.say(“I love CS10!”)

>>> Sprite.say(NewSprite, “I love CS10!”)

21 of 39

Inheritance and Subclasses

22 of 39

When do we want subclasses?

  • What if we wanted to make multiple Alonzos with different names instead of just one?�
  • We can make an Alonzo subclass or child class that inherits from Sprite

23 of 39

Review: Subclasses and Inheritance

  • A subclass is a class that shares certain attributes and methods with another class, called the superclass or base class

  • We call this type of data sharing inheritance.

  • Sometimes, we call the base class the parent and the subclass the child (as with genetic inheritance)

24 of 39

Subclasses

class Alonzo(Sprite):

color = ‘yellow’

antenna = True

def __init__(self, name, color):

self.name = name

def say(self, text):

print(“CS10 WOO!”)

25 of 39

Inheritance: Selective Sharing

  • A couple of things to note:
    • The class declaration takes in a Sprite object as an input
      • This is how we know that Alonzo is a subclass of Sprite
    • We’ve added color and antenna as a class attribute
    • We’ve changed the __init__ method to only set the name
    • We’ve written a new ‘say’ function

  • What do you think will happen when we call the functions of an Alonzo object compared to calling the functions of a Sprite object?

26 of 39

Checking Your Understanding: WWPP

What would Python print in the following script?

>>> SpriteOne = Sprite(‘One’, ‘green’)

>>> SpriteTwo = Alonzo(‘Alonzo’, ‘blue’)

>>> SpriteTwo.say(‘It’s a nice day out’)

  1. It’s a nice day out
  2. CS10 WOO!

27 of 39

Checking Your Understanding: WWPP

What would Python print in the following script?

>>> SpriteOne = Sprite(‘One’, ‘green’)

>>> SpriteTwo = Alonzo(‘Two’, ‘blue’)

>>> SpriteTwo.say(‘It’s a nice day out’)

  • It’s a nice day out
  • CS10 WOO!

28 of 39

Checking Your Understanding: WWPP

What would Python print in the following script?

>>> SpriteOne = Sprite(‘One’, ‘green’)

>>> SpriteTwo = Alonzo(‘Two’, ‘blue’)

>>> SpriteTwo.say(‘It’s a nice day out’)

  • It’s a nice day out
  • CS10 WOO!

29 of 39

Checking Your Understanding: WWPP

What would Python print in the following script?

>>> SpriteOne = Sprite(‘One’, ‘green’)

>>> SpriteTwo = Alonzo(‘Two’, ‘blue’)

>>> SpriteTwo.say(‘It’s a nice day out’)

  • It’s a nice day out
  • CS10 WOO!

What would SpriteOne.say(‘It’s a nice day out’) print?

‘It’s a nice day out’

30 of 39

Checking Your Understanding: WWPP

What would Python print in the following script?

>>> SpriteOne = Sprite(‘One’, ‘green’)

>>> SpriteTwo = Alonzo(‘Two’, ‘blue’)

>>> SpriteTwo.size

  • 100
  • 1000
  • 10000

31 of 39

Checking Your Understanding: WWPP

What would Python print in the following script?

Would this print the same result as SpriteOne.size? Yes / No

>>> SpriteOne = Sprite(‘One’, ‘green’)

>>> SpriteTwo = Alonzo(‘Two’, ‘blue’)

>>> SpriteTwo.size

  • 100
  • 1000
  • 10000

32 of 39

Checking Your Understanding: WWPP

Why would the first result give different outputs, but the second result gives the same output?

33 of 39

Dot Expression Rules

<expression>.<name>

How to evaluate:

  1. Evaluate <expression>, which yields an object.
  2. <name> is matched against the instance attributes of that object; if an attribute with that name exists, its value is returned.
  3. If not, the name is looked up in the class, which yields a class attribute value. If it is not found in the class, look in any superclasses.
  4. That value is returned unless it is a function, in which case a bound method is returned instead.

34 of 39

Dot Expression Rules

>>> lonzo = Alonzo(‘Lonzo’, ‘purple’)

>>> lonzo.name # found in instance

‘Lonzo’

>>> lonzo.size # found in Sprite

‘100’ superclass

>>> lonzo.color # found in Alonzo

‘yellow’ class

35 of 39

Inheritance: Selective Sharing

  • Just like you are not an identical copy of your parents, subclasses are not identical copies of their base classes.

  • Subclasses inherit some attributes and methods from their parent classes, but also contain some unique data.

  • Just like Snap!, in Python methods and attributes in the subclass have precedence over those in the parent class. These methods and attributes override the parent class.

  • Even a subclass can be a superclass for another child!

36 of 39

Subclass Practice

Subclass: Alonzo

  • All Alonzo sprites start out at 100% size
  • All Alonzo sprites have a unique name but the same color (“yellow”) and antenna
  • Always says “CS10 WOO!”�

Alonzo subclass: Terminalonzo

  • All sprites have an antenna and the same color: “grey”
  • All sprites have a unique name starting with “T-”
  • Always says “I’LL BE BACK”

37 of 39

Let’s Design Terminalonzo

class Terminalonzo(_______):

________________

def __init__(self, name, color):

__________________

def say(self, text):

__________________

38 of 39

Let’s Design Terminalonzo

class Terminalonzo(Alonzo):

color = ‘grey’

def __init__(self, name, color):

self.name = “T-” + name

def say(self, text):

print(“I’LL BE BACK”)

  • Why don’t we need a size or an antenna attribute? Because Terminalonzo inherits it from Alonzo!

39 of 39

Summary

  • Classes in Python produce instances of objects of the same class
  • Objects include two different kinds of data
    • Class attributes, which belong to all objects of a class
    • Instance attributes, which belong to specific instances of a class
  • Subclasses can inherit some attributes from parent classes, but can override them too
  • When using dot notation, you look first in the instance, then the class, and any parent/superclasses for the method or attributes