15-112 Spring 2013 Quiz 8

* 15 Minutes.  No calculators, no notes, no books, no computers.

1.       [35 pts.  5 pts each] Short Answers.  Be very brief.

a.       In any method, the first parameter is always "self".  Very briefly, what is stored in that parameter?

b.      Give one obvious case where a classmethod would be useful.

c.       In just a few words, give one obvious case where inheritance would be useful.

d.      What is the main distinction between  __str__ and __repr__?

e.      What method in a class must be implemented properly in order to add an instance of that class to a set?

f.        What method in a class must be implemented properly in order to compare two instances of that class for equality?

g.       When does the default test for equality return True (if you do not override it with an equality test of your own)?
 

2.        [65 pts]  Write the Rect and Square classes so the following test code works.  Note that your Square class may only have one method, __init__.
    assert(Rect.foo() == "bar")
    assert(str(Rect(2,3)) == "<2x3 Rectangle>") # Note it says Rectangle, not Rect
    assert(Rect(2,3).area() == 6)
    assert(isinstance(Square(5), Rect) == True)  
    assert(str(Square(5)) == "<5x5 Square>")
    assert(Square(5).area() == 25)   
    # Curiously, we'll say 2 Rects are equal if their areas are equal!
    assert(Rect(12,3) == Square(6))
    assert(Rect(12,3) != Rect(12,4))
    assert(Rect(12,3) != "Don't crash here!")

 

3.      Bonus/Optional [5 pts]:  What will this print?
y = 0
def g(x): global y; y+=1; return x+y
def h(x):
    for q in range(x): x = g(g(x)); return x
def f(g,x): return [h(i) for i in range(g(x))]
print f(g,3)  # 2.5 pts
y=0
print f(g,100)[-1]  # 2.5 more pts