CS 111 w20 lecture 18 outline
1 Practice
1.1 Mystery
class A: def __init__(self, x): self.x = x def bump(self, i): self.x += i class B: def __init__(self, x, y): self.x = x self.y = y def bounce(self, i): if i % 2 == 0: self.y += i self.x += i * 2 x = 7 a = A(x) a.bump(2) b = B(a.x, x) b.bounce(1) b.bounce(2) print(x, a.x, b.x, b.y)
1.2 Rectangle Class
class Point: def __init__(self, x, y): self.x = x self.y = y
- define a Rectangle class with three instance variables: a Point for the upper left corner, a width, and a height
- add a
get_corners
method to the class that returns a list of the rectangle's four corners
1.3 Fraction Class
What's missing from the definition?
class Fraction: def value(): return top / bottom
class Fraction: def __init__(self, top, bottom): self.top = top self.bottom = bottom def value(self): return self.top / self.bottom
- Are we able to treat these as fractions?
Fraction(3, 4) == Fraction(3, 4)
- add an
__eq__
method
- add an
Fraction(1, 2) < Fraction(3, 4)
- add a
__gt__
method
- add a
Fraction(1, 2) + Fraction(3, 4)
- add a
__add__
method
- add a
2 Cuckoo Class
class Cuckoo: def __init__(self, steps): self.steps = steps self.count = 0 def tick(self): self.count += 1 if self.count == self.steps: print("CUKCOO!!") self.count = 0 else: print("tick...") # more concise version using % def tick(self): self.count += 1 if self.count % self.steps == 0: print("CUKCOO!!") else: print("tick...")