python - california state university, northridgerenzo/cs432/notes/pythonintro.pdf · use module...

23
Python 1 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 *.py file

Upload: donga

Post on 22-May-2018

225 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 1Python

Scripting language: 1991 – other scripting languages: Tcl/Tk, RubyObject Oriented -- program can look like there are no classes…strong, dynamic typinggarbage collectorrun via its interpreter console (IDLE) or from *.py file

Page 2: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 2Indentation

indentation defines blocks no {…}

None is 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 + sTypeError: unsupported operand type(s) for +: 'float' and 'str'

Page 3: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 3numbers, lists

Numbers: integers, long, floats, complex (z.real and z.imag )builtin functions abs, max, pow, min, roundmath module sin, cos, pi, mod, log, sqrt, floor, …>>> x = (3 + 2j)>>> x.real3.0>>> x.imag2.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

Page 4: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 4

>>> 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, …operators in, not in, +, *, :methods append, count, extend, index, pop, remove, insert, sort

: slice operator – subsets

Page 5: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 5tuples, strings

tupes are 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 string for 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

Page 6: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 6>>> "You can't do it""You can't do it">>> 'She said, "Whats going on?" and left.''She said, "Whats going on?" and left.'>>> """This string goesover two lines."""'This string goes\nover two 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

maketrans creates a translation table for character substitution that is required by translate

Page 7: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 7DictionaryDictionary is a hashed associative array like Java's Hashtableimmutable key accesses mutable value

functions del deletes key-value pairlen number of key-value pairs

methods clear, 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

Page 8: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 8Structured Stmts

! boolean None, 0, empty values [], "", () are falseeverything 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

[elif expr :suite]n

[else:suite]1

A suite is a "block"of indented code

>>> x = 10>>> y = 3>>> if x < y:

z = y - xelif x > y:

z = x - yelse:

z = x>>> z7

In IDLE to de-indent a line enter control-[

The indentation doesn't look as pretty in the IDLE display

Page 9: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 9ifexample.py

Page 10: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 10while, for

While loopwhile expr :

suite[else :

suite]1

suites can containbreak continue

list = ['Terrence', 'this', 'is', 'stupid', 'stuff']for word in list:

print word

Terrencethisisstupidstuff

For loop iterates over a group of items –list, tuple

for expr in list : suite

[else :suite]1

Page 11: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 11Functions

>>> def fun1(x, y, z):value = x + 2*y + z**2return value

>>> u, v = 3,4 # u = 3; v = 4;>>> fun1(u, v, 2) # args by position y = v

15>>> fun1(u, z = v, y = 2) # args by name23>>> def fun2(x, y=1, z=1): # args w/ default values

return x + 2*y + z**2

>>> fun2(3, z=4)21>>>

def funName(arg0, arg1, *tup) : suitedef funName(arg0, arg1, *dict) : suite

collects all extra args into a tuple or dictionary

Page 12: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 12Classesclass className1 :

classVarName = valuedef __init__(self, arg0, arg1,…, argn):

self.var0 = arg0 # instance variableself.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 arg0 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 = xself.y = y

s = Shape(10, 20)

<< see quads.py andtestQuads.py >>

Page 13: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 13Tkinter

Tkinter is a Python module that is an OO version of the Tk (Toolkit) GUI from TclTk.

Tkinter GUI classes are like C# "control" classes, and Java Swing JComponents / JContainers.

A Tk application consists of widgets that have a parent-child (master-slave) relationship.

The toplevel root 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 Tkinter reference >>

Page 14: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 14Widget: options methods

widgetName = Frame (master, [optionValue]n )

optionValue : option = value

background = "colorName" background = #rrggbbcursor = "cursorName" cursor = "gumby"height = 200width = 100

Options are used to send widget attributes to the underlying Tk object

Widget have methods – some methods common to all widgets: widget.update() # redisplays the widgetwidget.wininfo_children() # returns list of childrenwidget.mainloop() # update, processing eventswidget.quit() # quit the mainloopwidget.grid_propagate(0) # use with height and width

options

Page 15: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 15Geometry 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 = intcolumn = introwspan = intcolumnspan = intsticky = expression

sticky = E + W allocates extra space horizontallysticky = NE places square in NorthEast corner

Each frame widget has its own grid management.

Geometry mgmt best done with hierarchical containment:nested frame's control the layout of their children

Page 16: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 16layout example

Create 3 widgets: 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 >>

Page 17: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 17Canvas

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, y2,[optionValue]n)example options:

fill = colorValuetags = stringValue # identifier for rectangleoutline = colorValue # border colorwidth = 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 || idfor example:canvasWidget.find_all() # returns list all object idscanvasWidget.delete (tagOrId)canvasWidget.find_closest (x, y, halo=None, start=None)

# returns tuple id of closest object to point x,y

Page 18: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 18EventsEvents 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 withunderlying Tk variable. Control variables aka property.def MyButton(Button):

def __init__(self, label, color):self.buttonText = StringVar() # init control var# use get() and set() on control variableself.buttonText.set(label) # change buttonText to change button labelButton.__init__(self, background = color,

command = self.clickEvent,textvariable = self.buttonText)

def clickEvent(self):self.buttonText.set(" press me again ")

Page 19: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 19bindEvents 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 canvas is 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 eventdef leftMouseClick(self, event):

print "mouse click at %d %d" & (event.x, event.y)

Page 20: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 20Instance Vs Class

Variable scope determined by name and position of use / initialization

Instance variables are used / initiated in constructor – __init__(…):self.varName # public instance variableself.__varName # private instance variablevarName # 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 instancevariables 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 …

Page 21: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 21Instance 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

Page 22: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 22Class scope

Superclass

methods variables __methods __variables

Class

methods variables __methods __variables

Objectinstance

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.

Page 23: python - California State University, Northridgerenzo/cs432/notes/PythonIntro.pdf · Use module string for splitting a string into words, ... Tkinter Python 13 ... layout example

Python 23Multiple 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 rightlook 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