Docsity

Understanding Frames, Objects, and Constants in Python: A Look at the Online Python Tutor, Slides of Introduction to Computing

Partial preview of the text

Download Understanding Frames, Objects, and Constants in Python: A Look at the Online Python Tutor and more Slides Introduction to Computing in PDF only on Docsity!

Frames and objects are real

Q : What do these drawings on paper have to do with real

programming?

A : Frames, objects, and variables are exactly what's being

created in Python.

 The Online Python Tutor shows them to you  The very curious can look at the Python module traceback; this is used by our cunittest module to print frame information.

So it's good to have a notation to talk about them.

The power of the "true name"

new constants violate_physics: 3 42 const_list lt_speed pi id 3 × 10 8

h 6 × 10

id

3 × 10

8 lt_speed "lt_speed = new" wouldn't change the global lt_speed. image source (surely not original): http://4.bp.blogspot.com/_c4VqqkgR0xY/ TLHr8YE7RxI/AAAAAAAAAzg/hlPsnjG_Q4k/ s1600/GENIE-1.gif But I have the true name id3 stored in constants. "constants.lt_speed = new" does change the value in id3.

def f(x, y): """Returns: x times square of y""" (^1) return x * (y**2) lt_speed = 3e print g(3) code with function call function definitions m E g: 1 3 def g(m): """Returns: energy equivalent of mass m""" (^1) E = f(m, lt_speed) (^2) return E

3 × 10

8 lt_speed x y f: 1 3 3 × 10 8

Stack of frames: When functions call functions

Two "live" frames (stack shown growing downwards, here)

def f(x, y): """Returns: x times square of y""" (^1) return x * (speed**2) lt_speed = 3e print g(3) code with function call function definitions m E g: 1 3 def g(m): """Returns: energy equivalent of mass m""" (^1) E = f(m, lt_speed) (^2) return E x y f: 1 3 3 × 10 8

Error messages show stack info

Traceback (most recent call last): ... line 2, in : print g(3) ... line 1, in g: E = f(m, lt_speed) ... line 1, in f: return x * (speed **2) NameError: global name 'speed' is not defined

3 × 10

8 lt_speed

Example for Conditionals

(Valentine's Day Special)

Flower num_petals he_loves_me

True id The number of petals. ≥ 0, initialized to random number. None if there are no petals. Otherwise, True if the next petal corresponds to "he loves me", False if it corresponds to "he loves me not".