Está en la página 1de 17

Quick Python Book

Chapter 1. About Python


-cross platform lunix/unix, windows, mac
-interpreted
-simple syntax, due to:
-dynamic typing: types being associated with objects, not variables
-operates at high level of abstraction
-well suited for rapid application development
-readable due to required indentation
-open-source
-python semicompiled into byte-code form executed by python interpreter
-python results in slower programs than fuly-compiled language like Chap
ter
-but easy to extend python with c/c++ modules to run CPU intensive porti
ons of programs
-C, java have larger collections of libraries available
-python doesn't check variable types at compile time
Chapter 2. Getting Started
-start a interactive session:
-on windows, Navigate to python.exe in Python 3.x submenu
-on mac, type python3 in terminal
-on unix, type python3.4 at command prompt
-idle: integrated development environment for python
-start idle on windows navigate to IDLE entry of python 3.4 submenu
-on mac, find IDLE in Python 3.x folder
-on unix, type idle3.4 at command prompt
-when using idle's python shell window, can:
-toggle through previous and next commands using alt-p, alt-n
-commands are buffered, can move around buffer using mouse, arrows keys
-can scroll or search up, place cursor on any line, and line wi
ll be copied to bottom of screen where it can be edited
-help() function help on modules, keywords, topics
-help(var) gives immediate display of var's types documentation
-dir() lists objects in particular namespace
-useful for finding out what methods and data defined for class
-i..e. dir(int)
Chapter 3. Quick Python Overview
-python's four number types:
-integers: 1, -3
-floats: 3.0 31e12
-complex numbers: 3 + 2j
-booleans: True, False
-arithmetic operators: +, -, *, /, ** (exponentiation), %
-division of integers with / results in a float, division of integers wi
th // results in truncation
-integers unlimited size
-list can contain mixture of other types as elements
-x = [], x = [1], x = [1,"two",3]
-can be indexed from front using positive integer (starting with 0 as fi
rst element)
-can be indexed from back using negative indices (with -1 as last elemen
t)
-obtain a slide using [m:n], when m is inclusive starting point and n is
EXclusive end point
-[m:] slice goes to lists end, [:n] slice starts at beginning
-can use this notation to add, remove, or replace elements in list
-size of list increases or decreases if new slice is bigger or smaller t

han slice replacing


-list methods: append, count, extend, index, insert, pop, remove, revers
e, sort
-can also use built-ins: len, max, mix on lists
-can also use operators, in, +, *
-tuples: similar to lists but immutable (can't be modified once created)
-operators in, +, * and built-ins len, max, min operate on same way as l
ists because none modify original
-index and slice notation works same as lists, but can't e used to modif
y elements
-tuple: x = (1,2,3)
-empty tuple: ()
-one element tuple: (1,)
-multi-element tuple: (1,"two", [1,2])
-list can be converted to tuple using built-in function tuple, tuple(x)
-tuple can be converted to list using built-in list function, list(x)
-strings: can be delimited by single quotes (' '), double quotes(""), and can co
ntain \t, \n
-strings immutable, operators and functions working on them return new s
trings derived from original
-operators (in, +, *), built-in functions (len, max, min) can op
erate on strings
-index and slice notation works on strings, but cant be used to
add, remove, or replace elements
-dictionaries: associative array functionality implemented using hash table
-built-in len functino eturns number of key-value pairs
-del can be used to delete key-value pairs
-number of dictionary methdos: clear, copy, get, has_key, itms, keys, up
date, values
-x = {1: "one", 2: "two"}
-x ["first"] = "one"
-keys must be immutable, string, number, or tuple
-value can be any kind of objects
-set: unordered collection of objects used where membership and uniqueness are m
ain things needed
-duplicates removed
>>> x = set([1, 2, 3, 1, 3, 5])
>>> x
{1, 2, 3, 5}
>>> 1 in x
True
-file object: for accessing files
-open used to create file- f = open("myfile", "w")
-OS module provide number of functions for moving around file system and
working with pathnames
-sys library module allows acces to stdin, stdout, stderr
-struct library provides support for reading and writing files generated
by C programs
-Pickle library module delivers data persistence through ability to easi
ly read and write python data types to and from files
-Boolean values and expressions: False is equivelant to 0, None, and empty value
s (i.e. "", [])
-everything else is considered True
-comparison operators: <, <=, ==, >, >=, !=, is, is not, in, not in)
-boolean operators: and, not, or
-if-elif-else: needs colons, syntax below
-if x < 5:
y = -1
elif x > 5:
y = 1

else:
y=0
-while loop: needs colons
-while x > 1:
x = x - 1
-can use break, continue statement
-for loop: allows iteration over any variable type, such as list
-item_list = [1,"two"]
for x in item_list:
print(x)
-function: defined using def statement
-return statement returns value
-exceptions can be caught and handled using try-except-finally-else compound sta
tement
-any exception tht isn't caught will cause program to exit
Part 2: The essentials
Chapter 4: The absolute basics:
-python uses indentation to determine block structure
-'#' character used to start a comment i.e. # comment
-neither variable type declaration nor end-of-line delimiter necessary
-variables created automatically when first assigned
-python variables can be set to any type of object
i.e. x = 5
x = "sup"
-del statement deletes variable i.e. del x
-division of two ints with / returns float, // returns int
-\ can be used to escape characters: \t, \n, \" , \', \\
-integers have unlimited range in python, i.e. 4
-float can be written with decimal point or using scientific notation, i.e. 3.14
-2E-8
-booleans are either True of False and behave identically to 1 and 0
-int(200.3) converts float to int, float(1) converts int to float
-built in numeric functions: abs, float, int, long, max, min, oct, hex, pow, rou
nd
-functions in math module include: acos, asin, atan, atan2, ceil, cos, cosh, e,
exp, fabs, floor, fmod, hypot, log, log10, mod, pi pow, sin, sinh, sqrt, tan
-None represents empty value
-can use input() function to get input from user, i.e. name = input("Enter Name:
")
-input always returns string
-python code conventions, only classes CapatalizeEachWord, all other identifiers
all lowercase, underscores_for_readability
Chapter 5: Lists, Tuples, Sets
-list is an ordered collection of objects i.e. x = [1, 2, 3]
-list automatically grows and shrinks as needed
-python lists can contain different types of elements
-len built-in function returns number of elements in list, i.e. len(x)
-list can be indexed from front using positive integer (starting with 0 as first
element) x[0]
-list can be indexed from back using negative indices (with -1 as last element)
x[-2]
-obtain a slice from list using [m:n], when m is inclusive starting point and n
is EXclusive end point
-[m:] slice goes to lists end, [:n] slice starts at beginning
-can use this notation to add, remove, or replace elements in list
-size of list increases or decreases if new slice is bigger or smaller t
han slice replacing
x[len(x):] = [5 , 6, 7] # appends list to end of list

x[:0] = [1,2] # appends list to start of list


x[1:2] = [] # removes second element in list
-list methods: append, count, extend, index, insert, pop, remove, reverse, sort
-append adds a single element to end of list, i.e. x.append(1)
-extend concatenates one list to another x.extend(y)
-insert(n, elem) inserts elem at index n of list, i.e. x.insert(2,"hello
")
-del deletes list items or slices, i.e. del x[1]
-remove method looks for first instance of given value inn list and remo
ves value from list, i.e. x.remove(3)
-if remove can't find anything to remove, raises an error (can
catch it)
-reverse method reverses list in place, i.e. x.reverse()
-sort method sorts list in place into ascending order for numbers and se
ts of strings, x.sort()
-all items in list must be of comparable types
-can use sort for custom sorting by defining function that will
return a key or value that we want to sort on, i.e.:
def compare_num_of_chars(string1):
return len(string1)
word_list.sort(key=compare_num_of_chars)
-can sort in reverse order by setting sort's reverse parameter t
o True
-in operator returns boolean value and tests if a value is in list, i.e. 3 in [1
,2,3,4]
#returns true
-+ operator concatenates two lists and leaves arguments unchanged, i.e. z = [1,2
] + [3,4]
-* operator produces a list of given size and initialized to given value , i.e.
z = [None] * 4
-min and max functions find smallest and largest items in list of comparable typ
es min([3,4,5,6])
-index function looks for list element equal to given value and returns location
of list element, i.e. x.index(5) # returns index if 5 is in list, returns error
if not
-count function returns number of times value is present in list, i.e. x.count(2
)
-slice notation returns shallow copy of list, i.e. if list contained in list, re
turns reference to list rather than copy
-deepcopy function returns independant copy of original
i.e. x = [1]
y=[x, [1,2]]
x[0]=2 # y[0][0] is now equal to 2
import copy
z = copy.deepcopy(y) #changing value of x will not affect z[0][0] now
-tuples: similar to lists but immutable (can't be modified once created, returns
error)
-operators in, +, * and built-ins len, max, min operate on same way as l
ists because none modify original
-index and slice notation works same as lists, but can't be used to modi
fy elements, i.e y = x[1:]
-tuple: x = (1,2,3)
-empty tuple: ()
-one element tuple: (1,)
-multi-element tuple: (1,"two", [1,2])
-tuple can't be modified, but if contain mutable objects (list, dictiona
ry), mutable object can be modified if assigned to its own variable
-tuple may appear on LHS of assignment, in which case variables recieve
corresponding values from tuple on RHS of assignment operator
i.e. (one,two,three,four) = (1,2,3,4) # now one = 1, two = 2, et
c.

-when doing assignment of this fashion, don't actually need the


brackets on LHS or RHS
-this allows for simple swapping of variables var1, var2 = var2,
var1
-python has extended unpacking feature allowing element marked with * to
absorb any number of elements not matching other elements
-i.e. x = (1,2,3,4)
a, b, *c = x # now c = [3,4]
-packing and upacking also possible with lists
-list can be converted to tuple using built-in function tuple (produces
new tuple), tuple(x)
-tuple can be converted to list using built-in list function (produces n
ew list), list(x)
-note: list function can also break string into character array
-set: unordered collection of objects used where membership and uniqueness are m
ain things needed
-duplicates removed
>>> x = set([1, 2, 3, 1, 3, 5])
>>> x
{1, 2, 3, 5}
>>> 1 in x
True
-x.add(element), x.remove(element) does what you expect
-x | y returns union of sets x and y
-& returns intersection of x and y
-^ returns xor of two sets
Chapter 6: Strings
-string is sequence of characters that can be accessed using index or slice nota
tion
-x = "hello" # x[0] is equal to h
-string can't be modified, must create new string (can use same variable)
-len(string_var) returns number of characters in string (like list)
-'+' is string concatenation operator, i.e. x = "Hello" + "World"
-'*' is string multiplication operator, i.e. 8 * "x" # returns "xxxxxxxx"
-special characters: \n,\t,\',\\,\v (vertical tab), \b (backspace)
-split function returns list of substrings in string
-uses any whitespace as delimiter for splitting (but can change that via
optional arg)
-can specifiy number of splits to return as optional second argument (ge
nerating list of n+1 substrings as elements or until runs out of string)
>>> x = "You\t\t can have tabs\t\n \t and newlines \n\n " \
"mixed in"
>>> x.split()
['You', 'can', 'have', 'tabs', 'and', 'newlines', 'mixed', 'in']
>>> x = "Mississippi"
>>> x.split("ss")
['Mi', 'i', 'ippi']
>>> x.split("ss",1)
['Mi', 'issippi']
-join takes list of strings and puts them together to form single string with or
iginal string between each element
-" ".join(["join","puts","spaces","between","elements"]) # returns 'join
puts spaces between elements'
-can use int or float functions to convert strings into integers or floating poi
nt numbers
-i.e. x = float("12.32") x = int("33")
-strip method returns new string removing any white space at beginning or end of
string, i.e. x.strip()
-lstrip removes whitespace only at left side

-rstrip removes whitespace only at right side


-can change which charachters strip, rstrip, lstrip remove by passing string con
taining chars to be removed
x = "www.python.org"
x.strip(".gorw") # returns python
-re module
-find function takes required arg (substring to search for), returns pos
itions of character of first instance of substring in string (or -1 if doesn't o
ccur)
-optional second arg is integer start, which says to ignore all
characters before position start
-optional third arg is integer end, which says to ignore charact
ers at or after end position in string
x = "mississippi"
x.find("ss",3) # returns 5
-rfind same as find, but starts search at end of string (same args)
-count returns number of non-overlapping times givven substring occurs i
n string
x.count("ss") # returns 2 against mississippi
-startswith, endswith looks for substring at beginning or end of string
-replace method replaces occurences of substring specified in first argument wit
h substring specified in second argrument
x = "Mississipi"
x.replace("ss","+") # Mi+i+pi
-string.lower() coverts to lowercase, string.upper() makes uppercase
-string.capitalize() capitalizes first character of string
-string.title() capitalizes all words in string
-string.isdigit() returns True if consists of digits
-string.isalpha() returns True if all alphabetic
-string.islower() if all lowercase
-string.isupper() returns True if all upper case
-repr function covnvers almost any object into some sort of string representatio
n
>>> repr([1, 2, 3])
'[1, 2, 3]'
-can be used for debugging to print contents of variable
-pirnts formal string representation
-str function produces printable string representation of any python object
-prints informal string representation
-format method combines format string containing replacement fields marked with
{ } with replacement values taken from parameters given to format command
>>> "{0} is the {1} of {2}".format("Ambrosia", "food", "the gods")
'Ambrosia is the food of the gods'
-string modulus operator % takes two parts: left side containing string, right s
ide containing tuple
-scans left string for formatting sequences and produces new string by s
ubstituting values on right side for formatting sequences in order
->>> "%s is the %s of %s" % ("Ambrosia", "food", "the gods")
'Ambrosia is the food of the gods'
>>> "Pi is <%-6.2f>" % 3.14159 # use of the formatting sequence: % 6.2f
'Pi is <3.14 >'
Chapter 7 Dictionaries
-dictionary is associative array implemented with hash table
-empty dictionary: x = {}
-once created, values may be stored in dictionary as if it were list, i.e. x[0]
= 'sup'
x[1] = 'nm'
-however, cannot assign position in list that doesn't already exist, can
only do so with dictionary

-new positions created in dictionary as necessary


-once assigned, values in dictionary can be accessed using key, i.e. print(x[0])
-can define dictionary as series key/value pairs: >>> english_to_french = {'red'
: 'rouge', 'blue': 'bleu', 'green': 'vert'}
-len function returns number of key/value pairs in dictionary >>> len(english_to
_french) #3
-keys method can be used to obtain all keys in dictionary : >>> list(english_to_
french.keys())
-can be used to loop through entries of dictionary
-values method can be used to obtain all values in dictionary: >>> list(english_
to_french.values())
-items can be used to return all keys and associated values as sequence of tuple
s:
>>> list(english_to_french.items())
[('green', 'vert'), ('blue', 'bleu'), ('red', 'rouge')]
-del statement can be used to remove key/value pair from dictionary: del english
_to_french['green']
-in keyword returns True if dictionary has value stored under given key, and Fal
se otherwise: >>> 'red' in english_to_french
-attempting to access key that is not present in dictionary is error, so
use in to test first
-get function returns value assocaited with key and if key not present returns s
econd argument passed to method
-if no second argument is included, get returns None if key no present
>>> print(english_to_french.get('blue', 'No translation'))
-setdefault method gets key's value, and if key not present, sets keys value in
dictionary to second argument
print(english_to_french.setdefault('chartreuse', 'No translation'))
-copy method obtains copy of dictionary: i.e. y = x.copy()
-deepcopy method makes deepcopy of dictionary for case where dictionary contains
modifiable object as values
-update method updates first dictionary with all key/value pairs of second dicti
onary
-for any common keys, values from second dictionary override those of fi
rst
z = {1: 'One', 2: 'Two'}
x.update(z)
-any python object that is immutable and hashable can be used as key to dicttion
ary, i.e. numbers, strings, tuples containing immutable values
-dictionaries great for caching for time-consuming operations that only occur on
small set of different combinations of arguments (that an be represented by tup
le of immutable values)
i.e.
sole_cache = {}
def sole(m, n, t):
if (m, n, t) in sole_cache:
return sole_cache[(m, n, t)]
else:
# . . . do some time-consuming calculations . . .
sole_cache[(m, n, t)] = result
return result
__
|Ch|apter 8 - The Control Loop 90 - 103
|__|
-syntax of while loop (note else is optional and only useful when there is break
in loop)
while condition:
body
else:

post-code
-break statement while loop terminates while loop and does not execute post-code
in else clause
-continue causes remained of body to be skipped in current iteration
-syntax of if-elif-else construct:
if condition:
body
elif condition:
body
else:
body
-can use pass statement as placeholder where statement is needed (i.e. body of i
f), i.e. pass
-for loop iterates over values returned by any iterable object
-list, tuple, string, or special function called range, or special type
of function called generator
-for syntax (note else is optional)
for item in sequence:
body
else:
post-code
-body executed once for each element of sequence and 'item' variable set
to be each element in sequence
-range(n) returns a sequence 0,1,2,...,n-1 that can be used for iteration on
x = [1, 3, -7, 4, 9, -5, 4]
for i in range(len(x)):
if x[i] < 0:
print("Found a negative number at index ", i)
-range(n,m) returns a sequence n, n+1, ...,m-2,m-1
-if m>=n, returns empty sequence
-range(n,m,z) returns a sequence: n, n+z, n+2z,...,m-2z,m-z
i.e. range(5,0,-1) returns 5, 4, 3, 2, 1
-can iterate through tuples instead of usual single variable using for loop with
tuple unpacking
somelist = [(1, 2), (3, 7), (9, 5)]
result = 0
for x, y in somelist:
result = result + (x * y)
-enumerate function returns tuples (index, item) to loop through both items and
index
x = [1, 3, -7, 4, 9, -5, 4]
for i, n in enumerate(x):
if n < 0:
print("Found a negative number at index ", i)
-zip function takes corresponding elements from one or more iterables and combin
es them into tuples until it reaches end of shortest iterable
>>> x = [1, 2, 3, 4]
>>> y = ['a', 'b', 'c']
>>> z = zip(x, y)
>>> list(z)
[(1, 'a'), (2, 'b'), (3, 'c')]
-list or dictionary comprehension is one-line for loop that creates a new list o
r dictionary from another list
new_list = [expression for variable in old_list if expression]
new_dict = {expression:expression for variable in list if expression}

example lwithout expression to create new list:


>>> x = [1, 2, 3, 4]
>>> x_squared = [item * item for item in x]
>>> x_squared
[1, 4, 9, 16]
example with expression to create new list
>>> x = [1, 2, 3, 4]
>>> x_squared = [item * item for item in x if item > 2]
>>> x_squared
[9, 16]
example without expression to create new dictionary
>>> x = [1, 2, 3, 4]
>>> x_squared_dict = {item: item * item for item in x}
>>> x_squared_dict
{1: 1, 2: 4, 3: 9, 4: 16}
-multiple statements can be placed on same line if separated by semicolon
x = 1; y = 0; z = 0
-can explicitly break up statement across multiple lines using backslash
>>> print('string1', 'string2', 'string3' \
, 'string4', 'string5')
-in 0 or empty values (i.e. empty string, list, dictionary, None) are false, and
any other values are true
-comparison operators: <, <=, >, >=, ==, !=, <>
-in and not in operators can be used to test membership in sequences (lists, tup
les, strings, dictionaries)
-boolean operators: and, or, not
-and operator returns first false object that expression evaluates to or the las
t object
-or operator returns first true object or last object
>>> [] and 5
[]
-== and != tests if operands contain same values,
-is operator and is not operator test to see if operands are the same object
i.e. >>> x = [0]
>>> y = [x, 1]
>>> x is y[0]
True
Chapter 9 - Functions
-basic syntax for python function definition:
def name(param1, param2,...):
""" Documentation string describing external behavior of function and pa
rams """
""" Docstring can be multiline """
body
>>> def fact(n):
...
"""Return the factorial of the given number."""
...
r = 1
...
while n > 0:
...
r = r * n
...
n = n - 1
...
return r
-if no explicit return is executed in procedure body, then None value returns
-although all functions return values, no need to capture functions return value

in variable
-positional parameter: specify definition variable names for each parameter, and
when function is called parameters used in calling code matched to parameter ba
sed on order
-i.e. example shown in fact(n)
-requires number of parameters used in calling code matches number of pa
rameters in function definition
-function parameters can have default values, which are declared by assigning de
fault value in first line of function definition
-i.e. def fun(arg1, arg2=default2, arg3=default3, . . .)
-any number of params can have default values, but must be defined as la
st params in param list
>>> def power(x, y=2):
...
r = 1
...
while y > 0:
...
r = r * x
...
y = y - 1
...
return r
>>> power(3,3) ; power(3)
-can pass arguments into function using name of corresponding function parameter
rather than its position
>>> power(y=2, x=3)
9
-called keyword passing
-useful when defining function with large number of possible arguments,
that mostly have common defaults
-prefixing final parameter name of function a * causes all excess nonkeyword arg
uments in a call of function to be assigned as a tuple to given parameter
>>> def maximum(*numbers):
...
if len(numbers) == 0:
...
return None
...
else:
...
maxnum = numbers[0]
...
for n in numbers[1:]:
...
if n > maxnum:
...
maxnum = n
...
return maxnum
-arguments passed by object reference and parameter becomes new reference to obj
ect
-so changes to immutable objects (i.e. strings, tuples, numbers) has no
effect outside function
-changes to mutable objects (i.e. list, dictionary, class) persist outsi
de function
-but reassigning parameter has no effect outside function
-can explicitly access global variable existing outside function using global st
atement
a="one"
def changeGlobal():
global a
a = 1
changeGlobal() <- a is now 1
-nonlocal statement is similar to global, but causes identifier to rever to prev
iously bound variable in closest enclosing scope
-global only acesses top level variable
-generator function can be used to define own iterators
-returns each iterations value using yield keyword
-when no more iterations, empty return statement or flowing of end of fu

nction ends iterations


-local variables in generator function saved from one call to ne
xt
def four():
x = 0
while x < 4:
print("in generator, x =", x)
yield x
x+ = 1
for i in four():
print(i)
in
0
in
1
in
2
in
3

generator, x = 0
generator, x = 1
generator, x = 2
generator, x = 3

-can use generator with in clause to see if value is in series generator produce
s
>>> 2 in four()

Chapter 10. Modules and Scoping Rules 115 - 128


-module is file containing code
-defines group of python functions or other objects, and name of module
is derived from name of file
-usually python code, but can also be c or c++ object files
-to create module, create text file named modulesname.py and enter python code
example <mymath.py>:
"""mymath - our example math module"""
pi = 3.14159
def area(r):
"""area(r): return the area of a circle with radius r."""
global pi
return(pi * r * r)
-get definitions for constants and function definitions in module using import s
tatement
example:
>>> import mymath
>>> pi
Traceback (innermost last):
File "<stdin>", line 1, in ?
NameError: name 'pi' is not defined
>>> mymath.pi
3.1415899999999999
>>> mymath.area(2)
12.56636
-can specifically ask for names from module to be imported in such a matter you
dont need to qualify it with module name

example:
>>> from mymath import pi
>>> pi
3.1415899999999999
-import statement takes three different forms:
-import modulename
-search for ptyhon module of given name, parses contents, makes
it available
-importing code to names within module must still be prepended w
ith module name
-from modulename import name1, name2, name3, ...
-each name1, name2, ... from within module name made available t
o importing code
-name1, name2,.. can be used without prepending modulename
-from module import *
-imports all public names from module name (all that dont begin
with an underscore )
-if two modules imported this way define same name, then second
module will replace name from first
-python looks for modules in variable called path, which can be accessed through
module named sys
>>> import sys
>>> sys.path
_list of directories in the search path_
-python searches each directory in list when attempting to execute impor
t, and first module that satisfies import request used
-if no module found, ImportError exception raised
-sys.path variable initalized from value of environment variable PYTHONPATH, if
it exists
-wherever script is run, sys.path variable for script has directory cont
aining scrip inserted as first element
-in order to ensure programs can use your python modules, must do one of followi
ng:
-place module in one of directories python normally searches for modules
-place all modules used by python program into same directory as program
-create a directory that will hold moduels, and modify sys.path variable
so includes new directory
-prepend name of variable or function in module with _ if you want name to be pr
ivate to within module (i.e. will not be imported with from ... import *)
namespace in python is a mapping from identifiers to objects usually represented
as dictionary
-when block of code is executed in python it has three namespaces, local, global
, and built-in
-variable encountered in execution first searched for in local name-spac
e, if doesn't exist, checks global namespace, if doesn't exist checks built-in n
amespace
-if variable not present in all three namespaces, NameError exception oc
curs
-built-in functions include len, min, max, int, float, long, list, tuple
, cmp, range, str,and repr
python script.py arg1 arg2
Ch 11. Python Programs 129-146

import sys
def main():
print("this is our second test script file")
print(sys.argv)
main()
If we call this with the line
python script2.py arg1 arg2 3
we get
this is our second test script file
['script2.py', 'arg1', 'arg2', '3']
You can see that the command-line arguments have been stored in sys.argv as a li
st of
strings.
Ch 12. Using the filesystem 147 - 158
Ch 13. Reading and writing files: 159 - 171
Ch 14. Exceptions 172 but skip to 176 - 185
Ch 15. Classes and OO programming 186 - 209
-class in python is effectively a data type
-define class with class statement
class MyClass:
body
-body is list of python statements, typically variable assignements and function
definitions
-once class is defined, new instance of class can be created by calling class na
me as function
instance = MyClass()
-class can be used as structures or records
-fields of instance don't need to be declared ahead of time, but can be
created on the fly
>>> class Circle:
...
pass
...
>>> my_circle = Circle()
>>> my_circle.radius = 5
>>> print(2 * 3.14 * my_circle.radius)
31.4
-fields of an instance can be accessed using dot notation as shown above
-can initialize fields of instance automatically by including an _init_ initiali
zation method in class body
-function is run every time instance of class is created, with new insta
nce as first argument
-_init_ method similar to constructor, initializing fields of class
-note self is always the name of the first argument in _init_
class Circle:
def __init__(self):
self.radius = 1
my_circle = Circle()
print(2 * 3.14 * my_circle.radius)

my_circle.radius = 5
print(2 * 3.14 * my_circle.radius)
-in above case, radius is instance variable of Circle instance (each instance of
Circle class has own copy of radius)
-can create instance variables as necessary by assigning them to field of class
instance
instance.variable = value
-method is function associated with particular class
-note all use of instance variables - both assignment and access - requi
re expliction metioning of containing instance in form instance.variable
-so methods in class must take self as argument as well
-first argument of any method is instance was invoked by/on named 'self'
by convention
-invoked with dot notation
>>> class Circle:
... def __init__(self):
...
self.radius = 1
... def area(self):
...
return self.radius * self.radius * 3.14159
>>> c = Circle()
>>> c.radius = 3
>>> print(c.area())
28.27431
-methods can be invoked with arguments, if method definitions accept those argum
ents
class Circle:
def __init__(self, radius = 1):
self.radius = radius
def area(self):
return self.radius * self.radius * 3.14159
c = Circle(5)
-class variable is variable associated with class, rather than instance of class
-can be accessed by all instances of class
-class variable created by assignment in class body, rather than _init_
function
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
def area(self):
return self.radius * self.radius * Circle.pi
>>> Circle.pi
3.1415899999999999
-python allows invokation of static methods even when no instance of class has b
een created
-must use @staticmethod decorator
"""circle module: contains the Circle class."""
class Circle:

"""Circle class"""
all_circles = []
pi = 3.14159
def __init__(self, r=1):
"""Create a Circle with the given radius"""
self.radius = r
Circle.all_circles.append(self)
def area(self):
"""determine the area of the Circle"""
return Circle.pi * self.radius * self.radius
@staticmethod
def total_area():
total = 0
for c in Circle.all_circles:
total = total + c.area()
return total
>>> import circle
>>> c1 = circle.Circle(1)
>>> c2 = circle.Circle(2)
>>> circle.Circle.total_area()
15.70795
>>> c2.radius = 3
>>> circle.Circle.total_area()
31.415899999999997
-classmethod also does not need instance of class before being invoked
-but method implicitly passed name of class as parameter so no need to h
ardcode name of class into function
-can also just avoid problem by using self._class_ in place of ClassName
-must place @classmethod decorator before method def
"""circle module: contains the Circle class in circe_cm.py."""
class Circle:
"""Circle class"""
all_circles = []
pi = 3.14159
def __init__(self, r=1):
"""Create a Circle with the given radius"""
self.radius = r
self.__class__.all_circles.append(self)
def area(self):
"""determine the area of the Circle"""
return self.__class__.pi * self.radius * self.radius
@classmethod
def total_area(cls):
total = 0
for c in cls.all_circles:
total = total + c.area()
return total
>>>
>>>
>>>
>>>

import circle_cm
c1 = circle_cm.Circle(1)
c2 = circle_cm.Circle(2)
circle_cm.Circle.total_area()

-inheritance example: shapes for drawing program, all need positions


-so abstract all shapes into shape class that has position extend class
for each actual shape

class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, delta_x, delta_y):
self.x = self.x + delta_x
self.y = self.y + delta_y
class Square(Shape): <--- note shape
def __init__(self, side=1, x=0, y=0):
super().__init__(x, y) <- must call _init_ of superclass using s
uper() function
self.side = side
class Circle(Shape):
def __init__(self, r=1, x=0, y=0):
super().__init__(x, y)
self.radius = r
-two requirements for inheritance in python
-must define inheritance hierarchy by typing name of superclass in brack
ets immediately after name of class being defined with class keyword
-must call _init_ method of superclass by using super function
-could also call superclasses method by naming inherited class u
sing Shape._init_(self,x,y)
-subclasses inherit instance variables, class variables, and methods of supercla
ss
c = Circle(1)
c.move(3,4)
-private variable and private methods cannot be seen outside of methods of class
in which its defined
-any method or instance variable whose name begins and doesn't end with
a double underscore __ is private
class Mine:
def __init__(self):
self.x = 2
self.__y = 3
def print_y(self):
print(self.__y)
>>> m = Mine()
>>> print(m.x)
2
>>> print(m.__y) <-- __y private
Traceback (innermost last):
File "<stdin>", line 1, in ?
AttributeError: 'Mine' object has no attribute '__y'
-when in method of class, have direct access, in order, to:
-local namespace: parameters and variables declared in the method
-global namespace: functions and variales declared at module level
-built-in namespace: built-in functions and built-in exceptions

-private superclass instance variables, methods, and class variables cannot be a


ccessed using self
-destructor can be defined for class, but creating and calling destructing no no
t necessary to ensure memory used by instance is freed
-python provides automatic memory management
-python implicitly calls destructor method __del__ just before instance is remov
ed upon reference count reaching zero
-can be used to ensure cleanup method is called
class SpecialFile:
def __init__(self, file_name):
self.__file = open(file_name, 'w')
self.__file.write('***** Start Special File *****\n\n')
def write(self, str):
self.__file.write(str)
def writelines(self, str_list):
self.__file.writelines(str_list)
def __del__(self):
print("entered __del__")
self.close()
def close(self):
if self.__file:
self.__file.write('\n\n***** End Special File *****')
self.__file.close()
self.__file = None
-similar to __init__, __del__ destructor of class's parent needs to called expli
citly with a class's own destructor
Ch 16. 290 - 304
-python places no restrictions on multiple inheritance
-example inheritance hierarchy:
class
. . .
class
. . .
class
. . .
class
. . .
class
. . .
class
. . .
class

E:
F:
G:
D(G):
C:
B(E, F):
A(B, C, D):

-when seeking methods, variables for inheritance, superclasses are searched in o


rder they are referenced following class statement
-