Python Objects, Classes




CS156

Chris Pollett

Feb 13, 2012

Outline

Function Scoping, Functions as Variables

  • By default variables used in a function definition are local.
    i = 5
    def printi():
       i=4
       print i
    printi() # outputs 4
    print i #outputs 5
    #note without the i=4 assignment would get i=5
    
  • To be able to modify a variable in global scope we must use the keyword global:
    def assign_i():
      global i
      i=3
    print i #now get 3
    
  • Function names can be treated as references to code in memory, so we can assign them to variables. i.e., We have function pointers and functions can be passed to other functions, etc:
    a = printi
    a() # prints 4
    
  • Python also supports anonymous function definitions:
    Consider:
    def f(x): return x**3
    f(10) #returns 1000
    
    g = lambda x: x**3 #notice don't use return with lambda
    g(10) #returns 1000
    
    def make_adder (n): return lambda x: x + n
    f = make_adder(2)
    g = make_adder(6)
    print f(42), g(42)
    
  • Anonymous function are often used to write "one-off" functions like callback handlers in GUI's and things.
  • Generators

    Coroutines

    Quiz

    Which of the following is true?

    1. Strings enclosed in two single quotes '' ... '' can span several lines in Python.
    2. The evaluation function used for Greedy Best First Search has the form `c(n) + h(n)` where `h` is a heuristic, and `c` is the cost to the given node.
    3. The Java code for(i = 0; i< 10; i++) {/* do something */} could be written in Python as:
          for i in range(0, 10):
             #do something
      

    Objects and Classes

    Inheritance, static methods, abstract classes.

    Tic-tac-toe Board Example