CS 61A

Time: Wed 10/18/17 6 pm

Extra Midterm 2 Practice

Vulcans (sp15-mt2-2)

  1. Draw the environment diagram that results from executing the code after the entire program is finished. No errors occur during the execution of this example.

    def scramble(egg):
      return [egg, over(egg)]
    
    def over(easy):
      easy[1] = [[easy], 2]
      return list(easy[1])
    
    egg = scramble([12, 24])

Pointers (sp16-mt2-1)

For each of the following code fragments, draw the final state of the program in boxes and arrows.

Extra Notes on __repr__()

Several scenarios while you are interacting with the Python interpreter.

'abc' # 'abc' - There are quotation marks around it
1 # 1 - There's no quotation mark around it

However, things can become interesting working with custom objects in terms of __repr__()!

class Foo:

  def __repr__(self):
    return 'abc'

f = Foo()
f # abc - There's no quotation mark around it

Compared to the following:

class Bar:

  def __repr__(self):
    return "'abc'"

b = Bar()
b # 'abc' - There are quotation marks around it

Take-Aways

However, when you are simply printing something out with print(), Python will display the __str__() of the object you passed to it.

When you are querying an statement/expression in REPL, Python will display the __repr__() of the object (if not None). You can think the following...

'howdy' # 'howdy'

As print(repr('howdy')), meaning you are printing out the repr for the string 'howdy'.

NB: Both __repr__() and __str__() needs to return strings.