CS 111 w20 lecture 17 outline
1 Objects
- pull back the veil, show what's been going on this whole time
- we've seen functions, and we've seen data
- objects are just the combination of these two things into a single entity
- you've been working with objects this whole time
1.1 Playing Card Class
import random class Card: def __init__(self, value, suit): self.value = value self.suit = suit def __repr__(self): if self.value <= 10: return str(self.value) + " of " + self.suit face = ["Jack", "Queen", "King", "Ace"][self.value - 11] return face + " of " + self.suit deck = [] for value in range(2, 15): for suit in ["Clubs", "Diamonds", "Spades", "Hearts"]: deck.append(Card(value, suit)) print("deck of", len(deck), "cards") random.shuffle(deck) print(deck[:5]) print(deck[0], ">", deck[1], deck[0] > deck[1])
1.2 Practice
1.2.1 Polls
1.2.2 Define a 2D Point class with fields x and y
class Point: def __init__(self, x, y): self.x = x self.y = y
1.2.3 What is printed by this code?
- "getter" and "setter" methods to access or modify fields
class Student: def __init__(self, name): print("Created new student object.") self.name = name self.major = "CS" def getMajor(self): print("Fetching major from the database.") return self.major def setMajor(self, new_major): print("Changing major to", new_major) self.major = new_major austin = Student("Austin") bao = Student("Bao") print("We made a class!") mA = austin.getMajor() mB = bao.getMajor() print(mA) print(austin.name)
1.3 History Class
- the
History
objects from lab 1 were just a class I wrote to provide list operations - classes can provide an interface for an internal data representation
- note the documentation strings (doc strings) in triple quotes, format strings, and raised exceptions
- doc strings allow documentation web page to be automatically generated
- raising exceptions allows more informative error messages