CS156
Chris Pollett
Sep 13, 2017
def countdown(n):
while n > 0:
yield n
n -=1
c = countdown(5)
print c.next() #prints 5
print c.next() #prints 4
print c.next() #prints 3
import time
def tail_log(f):
f.seek(0, 2) # 2nd arg: 0 means start of file, 1 means current pos, 2 means end of file
while True:
line = f.readline()
if not line:
time.sleep(0.1) # sleep 1/10 of a second
continue
yield line
def print_matches(text):
print "Trying to find", text
while True:
line = (yield)
if text in line:
print line
p = print_matches("hello")
p. next() #prints 'Trying to find hello'
p.send("lalalala la") #doesn't print anything
p.send("hello world") #prints hello world
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
class Stack(object): #this says stack inherits from object
a_class_variable = 5 # this var behaves like a Java static var
def __init__(self): #self = this in Java
self.stack = [] #now stack is a field variable of Stack
#in general using self.field_var is how we declare and
#instantiate a instance variable
def push(self, object): #the first argument of any method
self.stack.append(object) # is the object itself
def pop(self):
return self.stack.pop()
@property #properties are attributes that computes its value when accessed
def length(self):
return len(self.stack)
my_instance = Stack()
my_instance.push("hello")
print my_instance.length
print isinstance(my_instance, object) #returns True
print issubclass(Stack, object) #returns True
print type(my_instance) # returns <class '__main__.Stack'>
...
#etc
class Stack(list):
def push(self, object):
#could refer to parent by using syntax list.some_method_of_list
#or use super(list, self).some_method_of_list
self.append(object)
class MyClass:
@staticmethod
def my_method():
#some code
MyClass.my_method() #similar to Java
#load in abstract class module
from abc import ABCMeta, abstractmethod, abstractproperty
class MyClass:
__metaclass__ = ABCMeta # a metaclass is a class object that knows how to
# create other class objects. The default metaclass
# is type (Python 3, types.ClassType in Python 2).
# Here we are assigning ABCMeta
# to be used rather than type
# In Python 3, write MyClass(metaclass=ABCmeta)
@abstractmethod
def my_abstract_method(self):
pass
@abstractproperty
def my_abstract_property(self):
pass
class Board:
def __init__(self):
self.board = ["...", "...", "..."]
def add(self, player_piece, x, y):
if player_piece != "x" and player_piece != "o":
raise RuntimeError("Piece must be x or o")
row = ""
for i in range(3):
if i == y:
row += player_piece
else:
row += self.board[x][i]
self.board[x] = row
def draw(self):
for i in range(3):
print self.board[i]
b = Board()
b.add("x", 1, 1)
b.draw()
print
b.add("o", 0, 1)
b.draw()
Create a subclass of the Board class of the previous slide with a new method movePiece(self, x1, y1, x2, y2) which takes whatever the square is at location `(x1, y1)` and replaces the square at `(x2, y2)` with that value, then write a '.' at location `(x1, y1)` on the board. After your class definition, writes a few lines to test out your code.
Post your solutions to the Sep 13 In-Class Exercise Thread.
try:
statement_block_0
except SomeError1 as error_name1:
statement_block_1 #executed if a SomeError1 occurs
except SomeError2 as error_name2:
statement_block_2
...
finally:
statement_block_n # always gets executed
try:
f = open("file.txt", "r")
except IOError as e:
print e
raise RuntimeError("Something bad just happened")
class MyException(exception): pass
#now could use as:
raise MyException("Whoa! A MyException occurred!")
#more control can be had by overriding __init__
#here we define an exception taking two arguments
class MyException2(exception):
def __init__(self, errno, msg):
self.args = (errno, msg)
self.errno = errno
self.errmsg = msg
raise MyException2(403, "Access Forbidden")
import div #notice not div.py a, b = div.divide(198, 15) #notice function in div.py have to be prefixed with div.
import div as foo #now foo is the prefix
from div import divide #from div import *; would import all functions print divide(198, 15)
def fact(n):
"This function computes a factorial" #can use triple quoted strings
if(n <= 1): return 1
else: return n * fact(n - 1)
print fact.__doc__
import test help(test.fact)This would go to a screen that prints the documentation string.
pydoc test.factand get the same result as help(test.fact) before