Python Scripting language: 1991 – other scripting languages: Tcl/Tk ...

strawberriesfarctateSoftware and s/w Development

Nov 4, 2013 (4 years and 8 days ago)

88 views

Python1
Python
Scripting language: 1991 –other scripting languages: Tcl/Tk, Ruby
Object Oriented --program can look like there are no classes…
strong, dynamic typing
garbage collector
run via its interpreter console (IDLE) or from *.pyfile
Python2
Indentation
indentation defines blocks no {…}
Noneis an empty value
If function doesn't explicitly return a value None is returned.
#defines a comment for the rest of the line
Dynamically and strongly typed variables –assign a value to a
variable and you have typed it.
Type then determines operations.>>> f = 20.2
>>> s = "hello"
>>> t = f + s
Traceback(most recent call last):
File "<pyshell#95>", line 1, in -toplevel-
t = f + s
TypeError: unsupported operand type(s) for +: 'float'
and 'str'
Python3
numbers, lists
Numbers: integers, long, floats, complex (
z.realand z.imag
)
builtinfunctionsabs, max, pow, min, round
math modulesin, cos, pi, mod, log, sqrt, floor, … >>> x = (3 + 2j)
>>> x.real
3.0
>>> x.imag
2.0
Lists –like ArrayList, a dynamic, indexed, heterogeneous collection
>>> x = [1, "two", 3L, ["a", "hi stranger"], (5,6)]
>>> x
[1, 'two', 3L, ['a', 'hi stranger'], (5, 6)]
>>> x[3]
['a', 'hi stranger']
>>> x[3][1]
'hi stranger'
>>>>>> x[-3]
3L
negative indexes access from the
rear of the list
>>> import math
>>> math.cos(0.5)
0.87758256189037276
Python4
>>> y = x[1:3]
>>> y
['two', 3L]
>>> z = x + y
>>> z
[1, 'two', 3L, ['a', 'hi stranger'], (5, 6), 'two', 3L]
>>> z.reverse()
>>> z
[3L, 'two', (5, 6), ['a', 'hi stranger'], 3L, 'two', 1]
>>> len(z)
7
>>> w = [-1, 0] * 4
>>> w
[-1, 0, -1, 0, -1, 0, -1, 0]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
functions len, max, min, range, …
operatorsin, not in, +, *, :
methods append, count, extend, index, pop, remove, insert, sort
:slice operator –subsets
Python5
tuples, strings
tupesare immutable lists –used to store keys for dictionaries >>> t = ('a', 3L, "bye now")
>>> t
('a', 3L, 'bye now')
>>> l = list(t)
>>> l
['a', 3L, 'bye now']
>>> k = tuple(l)
>>> k
('a', 3L, 'bye now') Strings are immutable w/ many operators and functions
Use module stringfor splitting a string into words, finding and replacing
strings, changing case of words in a string
Use module re for regular expression pattern extraction functions
Python modules are specified with
import moduleName
Python6
>>> "You can't do it"
"You can't do it"
>>> 'She said, "Whatsgoing on?" and left.'
'She said, "Whatsgoing on?" and left.'
>>> """This string goes
over two lines."""
'This string goes\novertwo lines.'
>>> import string
>>> s = 'live and let live'
>>> string.translate(s, string.maketrans('i','o'))
'love and let love'
>>> s[3:11]
'e and le'>>> i = 20.5
>>> j = 30
>>> print "The value of i is %.2f and j is %d" % (i, j)
The value of i is 20.50 and j is 30
objects are automatically converted to strings for printing
maketranscreates a translation
table for character substitution
that is required by translate
Python7
Dictionary
Dictionary is a hashed associative array like Java's Hashtable
immutable key accesses mutable value
functionsdel deletes key-value pair
lennumber of key-value pairs
methodsclear, copy, get, has_keys, items, keys, update, values … >>> d = {'Apple':'ipod', "Brent's":'ruben'}
>>> d.keys()
['Apple', "Brent's"]
>>> d.items()
[('Apple', 'ipod'), ("Brent's", 'ruben')]
>>> d.get('intel', 'doh')
'doh'
>>> d.get("Brent's", 'doh')
'ruben'
>>> d["Brent's"] = 'pastrami on rye'
>>> d
{'Apple': 'ipod', "Brent's": 'pastrami on rye'}
optional string for key not found
Python8
Structured Stmts
! booleanNone, 0, empty values [], "", () are false
everything else is true (1 is true return value)
Standard comparison operators:
<, <=, <>, !=, ==, >=, >
in, not in, is, is not, and, not, or (<>
is an obsolete form of
!=
)
if expr:
suite
[elifexpr:
suite]n
[else:
suite]1
A suite is a "block"
of indented code
>>> x = 10
>>> y = 3
>>> if x < y:
z = y -x
elif x > y:
z = x -y
else:
z = x
>>> z
7
In IDLE to de-indent a line
enter control-[
The indentation doesn't look
as pretty in the IDLE display
Python9
ifexample.py
Python10
while, for
While loop
while expr:
suite
[else :
suite]1
suites can contain
breakcontinue
list = ['Terrence', 'this', 'is', 'stupid', 'stuff']
for word in list:
print word
Terrence
this
is
stupid
stuff
For loop iterates over a group of items –
list, tuple
for exprin list:
suite
[else :
suite]1
Python11
Functions
>>> def fun1(x, y, z):
value = x + 2*y + z**2
return value
>>> u, v = 3,4# u = 3; v = 4;
>>> fun1(u, v, 2) # argsby position y = v
15
>>> fun1(u, z = v, y = 2) # argsby name
23
>>> def fun2(x, y=1, z=1):# argsw/ default values
return x + 2*y + z**2
>>> fun2(3, z=4)
21
>>>
def funName(arg0, arg1, *tup) : suite
def funName(arg0, arg1, *dict) : suite
collects all extra argsinto a tupleor dictionary
Python12
Classes
class className1
:
classVarName= value
def __init__(self, arg0, arg1
,…,argn):
self.var0
= arg0 # instance variable
self.varn
= argn
def funName(self, arg0, arg1
,…,argn) : suite
class className2
(superClassName) :
def __init__(self, arg0, arg1
,…,argn):
# derived class must call super class _init_
superClassName.__init__(self, arg0, arg1,…,argn)
def funName(self, arg0, arg1
,…,argn) : suite
The self arg
0
used in class function definitions does not have an actual
argument (like calling C++ methods from C functions…)
class Shape :
def __init__(self, x, y):
self.x= x
self.y= y
s = Shape(10, 20)
<< see quads.pyand
testQuads.py>>
Python13
Tkinter
Tkinteris a Python module that is an OO version of the Tk(Toolkit)
GUI from TclTk.
TkinterGUI classes are like C# "control" classes, and Java Swing
JComponents/ JContainers.
A Tkapplication consists of widgets that have a parent-child (master-
slave) relationship.
The toplevelroot window is a Frame.
Frames are widgets that contain other widgets.
There are several widget layout mechanisms {pack, place, grid}
All Frames have grid layout capability –which will be discussed.
Other widgets: Button, CheckButton, RadioButton, Menu, MenuButton,
Canvas, Label, Entry, ListBox, Scale, ScrollBar, Text
<< see J. Simpson's on-line Tkinterreference >>
Python14
Widget: options methods widgetName= Frame (master, [optionValue]n
)
optionValue: option= value
background = "colorName"background = #rrggbb
cursor = "cursorName"cursor = "gumby"
height = 200
width = 100
Options are used to send widget attributes to the underlying Tkobject
Widget have methods –some methods common to all widgets:
widget.update()# redisplays the widget
widget.wininfo_children() # returns list of children
widget.mainloop()# update, processing events
widget.quit()# quit the mainloop
widget.grid_propagate(0) # use with height and width
options
Python15
Geometry mgmt
Grid is like a html table –widgets are placed in cells defined by:
row, column, rowspan, columnspan, …
the cell size is determined by the size of the widget
widgetName.grid([optionValue]n)
row = int
column = int
rowspan= int
columnspan= int
sticky = expression
sticky = E + W allocates extra space horizontally
sticky = NE places square in NorthEastcorner
Each frame widget has its own grid management.
Geometry mgmt best done with hierarchical containment:
nested frame's control the layout of their children
Python16
layout example
Create 3widgets: left1 (red, h 75, w 200) ,right (orange, 200, 200),
&bottom (yellow, -, 25) children of top level frame.
Then add 5 widgets: left2, left3, left4 (25, 25), left5(cyan, -,50) ,
left6 (green, -,100) as children of left1.…
self.bottom.grid(row = 1, column = 0,columnspan = 2,
sticky = E + W)
# put left1 extra space in row 2 (row 0 & 1 weights = 0)
self.left1.rowconfigure(2, weight = 1)
self.left6.grid(row = 2, column = 0, columnspan = 3,
sticky = E + W)
<< see TkGrid.py>>
Python17
Canvas
Canvas widget has methods for drawing shapes and creating windows:
line, arc, oval, rectangle, polygon, bitmap, image, text, window
canvasWidget.create_rectangle(x1, y1, x2, y
2,[optionValue]n)
example options:
fill = colorValue
tags = stringValue# identifier for rectangle
outline = colorValue# border color
width = intValue# border width
Each object created is a child of the canvas widget. It is given an object
id (int) numbered 1..n.
Often widget method arguments require a
TagOrId
value –a tag || id
for example:canvasWidget.find_all() # returns list all object ids
canvasWidget.delete(tagOrId)
canvasWidget.find_closest(x,y, halo=None, start=None)
# returns tupleid of closest object to point x,y
Python18
Events
Events are methods that are bound to user actions.
Button class has a command option that can be used to bind method.
Often widgets will have a control variable that can be associated with
underlying Tkvariable. Control variables akaproperty.def MyButton(Button):
def __init__(self, label, color):
self.buttonText= StringVar() # init control var
# use get() and set() on control variable
self.buttonText.set(label)
# change buttonTextto change button label
Button.__init__(self, background = color,
command = self.clickEvent,
textvariable= self.buttonText)
def clickEvent(self):
self.buttonText.set(" press me again ")
Python19
bind
Events are methods that are bound to user actions with bind()
widget.bind( "eventSequence", widget.methodName)
Example event sequences:
<Button-1> user pressed
first mouse button
<KeyPress-H>
user pressed the H key.
<Control-Shift-KeyPress-H> user pressed control-shift-H.
For example, assume self is a containing Frame widget and canvasis a
child Canvas widget. To bind the left button click to the method
leftMouseClick–
self.canvas.bind( "<Button-1>", self.leftMouseClick)

# event arg has information about the handled event
def leftMouseClick(self, event):
print "mouse click at %d %d" & (event.x, event.y)
Python20
Instance Vs Class
Variable scope determined by name and position of use / initialization
Instance variables are used / initiated in constructor –
__init__(…):
self.varName# public instance variable
self.__varName# private instance variable
varName# public method local variable
__varName# private method local variable
Class variables are used / initiated in the class body outside of any
method.
A Class variable can have the same name as an instance variable.
Python resolves scope by looking first in dictionary of instance
variables and then in dictionary of class variables.
Class variables can be used as default values for instance variables.
No class method –modules are "kinda like" class methods …
Python21
Instance scope
Built-in
functions
exceptions
Global
module
functions
module
variables
Local
arguments
local
variables
Reference in class method:
1.have direct access to the
local namespace.
2.search the Global
namespace
3.search the Built-in
namespace
Python22
Class scope
Superclass
methods
variables
__methods
__variables
Class
methods
variables
__methods
__variables
Object
instance
methods
variables
__methods
__variables
class variables w/ name collisions look like they are inherited,but
could have different values at different inheritance levels if initialized.
Python23
Multiple Inheritance
E
F
G
B
C
D
A
class E:
...
class F:
...
class G:
...
class B (E, F):
...
class C:
...
class D (G):
...
class A (B, C, D):
...
Search path to resolve reference not defined in local class:
look in base classes as declared –left to right
look in each class's ancestors before siblings ("height-first")
search for example: A, B, E, F, C, D, G
D. Harms, K. McDonald, The Quick Python Book, Manning, 2000