1 of 17

CSE 160 Section 9

Classes!

2 of 17

Logistics

  • Written check-in 8 due Friday Nov 21

  • Resubmission due Friday Nov 21
    • Fill out Form!

  • Coding Practice 8 due Sun Nov 23
    • Wait for autograder!

  • HW5 due Wednesday Nov 26

3 of 17

Classes

4 of 17

What is a Class?

A class encapsulates and abstracts data and logic that you can use in your programs

We want to make a program that can keep track of phone numbers.

5 of 17

Classes vs. Objects

A class is a blueprint- it defines what data and behavior an object will have

We can create an object instance from a class

Class

Multiple object instances

6 of 17

A Class Contains…

Variables / fields to hold the necessary data

A phone number should probably store:

  • Area code
  • Exchange
  • Number

7 of 17

A Class Also Contains…

Methods/behaviors to create, query, and modify an instance of a class

(Methods are basically functions inside classes)

A phone number should probably be able to:

  • Be created
  • Be called
  • Print its number

8 of 17

Creating an Instance of A Class

When we want to start using a class, we typically want to set some its variables to their correct values

This is done through a special method called __init__

When we create a phone number, we want to specify it’s area code, exchange, and number.

9 of 17

10 of 17

11 of 17

Problem 1

12 of 17

Problem 1a

What would the following client code print?

flower_shop = Shop(“Swansons”)

flower_shop.add_item(“Daisy”)

flower_shop.print_inventory()

13 of 17

Problem 1a

What would the following client code print?

flower_shop = Shop(“Swansons”)

flower_shop.add_item(“Daisy”)

flower_shop.print_inventory()

Output:

Daisy 1

14 of 17

Problem 1b

What code would you write to make a new shop called Arcane Comics that has 5 comics in it, and then print out it's inventory?

15 of 17

Problem 1b

What code would you write to make a new shop called Arcane Comics that has 5 comics in it, and then print out it's inventory?

comic_shop = Shop("Arcane Comics")

for i in range(5):

comic_shop.add_item("Comic")

comic_shop.print_inventory()

16 of 17

Problem 1c

Adding one item at a time is extremely tedious. Write a function for the class Shop called add_items that given an item and an amount, adds that amount to the store's inventory.

17 of 17

Problem 1c

Adding one item at a time is extremely tedious. Write a function for the class Shop called add_items that given an item and an amount, adds that amount to the store's inventory.

def add_items(self, item, amount):

if item not in self.inventory:

self.inventory[item] = 0

self.inventory[item] += amount