CSE 160 Section 8
Classes!
CSE 160: Classes
Logistics
CSE 160: Classes
Classes
CSE 160: Classes
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.
CSE 160: Classes
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
CSE 160: Classes
A Class Contains…
Variables / fields to hold the necessary data
A phone number should probably store:
CSE 160: Classes
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:
CSE 160: Classes
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.
CSE 160: Classes
CSE 160: Classes
CSE 160: Classes
Problem 1
CSE 160: Classes
Problem 1a
What would the following client code print?
flower_shop = Shop(“Swansons”)
flower_shop.add_item(“Daisy”)
flower_shop.print_inventory()
CSE 160: Classes
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
CSE 160: Classes
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?
CSE 160: Classes
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()
CSE 160: Classes
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.
CSE 160: Classes
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
CSE 160: Classes
Problem 2
Given the doc-strings and example output, fill in the code for each method in the StreamingService class.
CSE 160: Classes
Problem 2
Given the doc-strings and example output, fill in the code for each method in the StreamingService class.
Python Tutor
CSE 160: Classes