CS156
Chris Pollett
Sep 14, 2022
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 ABC, abstractmethod, abstractproperty class MyClass(ABC): # 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 ABC (need ABCmeta Python2) # to be used rather than type # In Python 2, write__metaclass__ = ABCMeta right after class line @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()
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
from math import floor def my_pow(x, y): """ Computes x raised to the power of y For example, >>> my_pow(3, 4) 81 Here are some base cases: >>> my_pow(0,0) 1 >>> my_pow(1,0) 1 >>> my_pow(2,0) 1 Since our method does something different when y is odd or even we have a test for each case: >>> my_pow(2,4) 16 >>> my_pow(2,5) 32 """ if y == 0: return 1 tmp = my_pow(x, floor(y/2)) tmp = tmp * tmp if y == 2 * floor(y/2): return tmp else: return tmp * x if __name__ == '__main__': #run as the main program from command line (as opposed to imported by #someone else import doctest doctest.testmod()