CSE 160 Section 9
Classes!
Logistics
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.
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
A Class Contains…
Variables / fields to hold the necessary data
A phone number should probably store:
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:
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.
Problem 1
Problem 1a
What would the following client code print?
flower_shop = Shop(“Swansons”)
flower_shop.add_item(“Daisy”)
flower_shop.print_inventory()
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
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?
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()
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.
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