introduction to python fred l. drake, jr. [email protected]
TRANSCRIPT
Introduction to Python
Fred L. Drake, [email protected]
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Overview
• What is Python?• Why use Python?• Compared to Other Languages• Basic Tutorial
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
• What is Python?
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
What is Python?
• Object-oriented rapid prototyping language• Excellent scripting language• Also a solid application language• Extensible
• C/C++/Fortran/whatever• Java (using Jython or JPE)
• Embeddable
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
“Good citizen” stuff
• Open source• Copyrighted but use is not restricted• Development on SourceForge
• Mature (11 years old)• Great user community
• Many books, & more to come• Newsgroups: comp.lang.python,
comp.lang.python.announce
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
High-level properties
• Elegant & easy to learn• “Executable pseudo-code”• Suitable as a first language
• Extremely portable• Linux, Unix, Mac OS, PalmOS, OS/2, BeOS,
Amiga, VMS, Cray, OS/390, ...• Sorry(!): Windows, WinCE, PocketPC
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
High-level properties, cont.
• Compiled to interpreted byte code• Compilation is implicit and automatic• Byte code is higher-level than Java byte code,
so performance is better for most applications
• Automatic memory management• Reference counting
• Predictable object destruction• Amortized cost for reclamation
• Cycle detector for circular references
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Safety
• Even security people won't talk about safety, why is it here?
• What we mean is:• Errors in Python code do not cause core dumps
(“GPF” on that other O/S)• Running out of virtual memory or recursing
infinately raises an exception the application can handle
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Interfaces to...
• Many GUI libraries• Platform independent
• Tk, wxWindows, GTK, Qt• AWT, Swing (using Jython or JPE)
• Platform dependent• SVGAlib, Mac OS, X11/Motif, MFC
• Open source and commercial databases• Java (using Jython or JPE)
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Language properties
●Everything is an object● Modules, functions, classes
●Dynamic typing, polymorphism●Exception handling●Static lexical scoping●Operator overloading
●And...
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Indentation!
●But...● C/C++/Perl/sh/whatever don't do that!● So why break with “tradition” ?● Why do you have it in for {curly braces} ?
●People indent anyway● Python is for people
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Indentation in Python
●Indentation is used to indicate structure● Just like in documents, white space is used to aid
navigation by the reader● Just as in a C program, programmer's use white
space to aid understanding● int main(int argc, char *argv[]) { if (argc > 1) printf("Found %d arguments.\n", argc - 1); else printf("No command-line arguments.\n"); return 0;}
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
High-level data types
• Numbers: int, long, float, complex• Strings: immutable, both 8-bit and Unicode• Containers: lists and dictionaries• Large library: binary data, sockets, regular
expressions, Web protocol connections• Extensions: modules can define new types
in Python, C, C++, whatever.
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
• Why use Python?
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Productivity!
●Reduced development time● Code is 2-10x shorter than C/C++/Java
●Improved program maintenance● Code is extremely readable
●Less training● Python is easy to learn
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
What is it used for?
• Rapid prototyping• Web scripting• Ad-hoc programming• Steering scientific applications• XML processing• Database applications• GUI applications• Extension language
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Who uses Python?
• Zope Corporation (Web application server)• RedHat (installation tools)• LANL, LLNL, Fermilab (steering)• ObjectDomain (extensible UML tool)• Industrial Light & Magic (everything)• Yahoo! Groups (formerly eGroups)• Google (many adjunct services)
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Exciting applications
• Zope – supercharged Web sites• Mailman – GNU mailing list manager• Jython – 100% Pure Java implementation• XML processing• Gnome/KDE scripting• Star Wars, Episode 1 !• Can do “Windows stuff” too (COM, ASP, ...)• Mozilla XPCOM support
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Typical Success Stories
• Prototype in Python• First to market• Acquisition• Re-write in C++/Java• e-shop (now MS Commerce Server),
411 (now Yahoo! Mail)
• Steering• Symbiosis of Python and C++ or Java• LANL, LLNL, ILM, Hubble Space Telescope
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
How far we've come...
• 1995: “Python? What's that?”
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
How far we've come...
• 1995: “Python? What's that?”
• 1997: “But nobody else uses Python!”
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
How far we've come...
• 1995: “Python? What's that?”
• 1997: “But nobody else uses Python!”
• 1999: “Where can I hire Python programmers?
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
• Compared to Other Languages
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Python vs. Perl
• Easier to learn• Important for occasional users
• More readable code• Easier maintenance
• Fewer “magical” side effects• More modular, better for large projects• Better Java integration• Less Unix bias
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Python vs. Tcl
• Object oriented• More differentiated syntax• Less need for C extensions• Extensions can't redefine syntax
• Hence fewer extension conflicts
• Better Java integration• Python uses Tk as de-facto GUI standard
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Python vs. Java
• Code is 5-10x more concise• Dynamic typing• Much quicker development
• No explicit compilation phase• Less typing
• Have your cake & eat it too:• Jython – 100% Pure Java Python interpreter• JPE – Call Java from Python using the JNI
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Jython
• Seamless integration with Java• Separate implementation• Implements the same language• Different set of standard modules
• But lots of overlap
• Differences in some “grey areas”• Some introspection is different• Command line options, etc.
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Java Integration
• Interactive• Create & use Java objects interactively• Great for testing Java code
• Compiles directly to Java byte code• Create class files from Python code• Run as applet in browsers
• Import Java class files directly• Subclass Java classes
• Pass instances back to Java
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
• Basic Tutorial
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Tutorial Outline
• Shell (numbers, strings, variables)• Lists (arrays), dictionaries (hashes)• Variable semantics• Control structures & functions• Classes & methods• Standard library
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Interactive “Shell”
• Great for:• Learning the language• Experimenting with the library• Testing your own modules
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Interactive Example
●Type statements or expressions at the prompt:
● >>> print "Hello, world"Hello, world>>> x = 12 ** 2>>> x / 272>>> # this is a comment
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Numbers
• The usual notations and operators• 12, 3.14, 0xFF, 0377, (-1 + 2) * 3 / 4**5,
abs(x), 0 < x <= 5
• C-style shifting & masking• 1 << 16, x & 0xff, x | 1, ~x, x ^ y
• Integer division truncates• 1 / 2 --> 0 # float(1) / 2 --> 0.5
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Numbers, cont.
• Long (arbitrary precision)• 2L ** 100 --> 1267650600228229401496703205376L
• Starting in Python 2.2:2 ** 100 --> 1267650600228229401496703205376L
• Complex• 1j ** 2 --> (-1+0j)
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Strings
" hello" + " world"" helloworld" # concatenation" hello" * 3 " hellohellohello"# repetition" hello" [0] " h" # indexing" hello" [-1] " o" # indexing (from end)" hello" [1:4] " ell" # slicinglen(" hello" ) 5 # length" hello" < " jello"1 # comparison" e" in " hello" 1 # search
" escapes: \n etc., \033, \xff etc."'single quotes'
'''triple quotes to spanmultiple lines'''
r" raw strings"
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Lists
● a = [99, 'bottles of beer', ['on', 'the wall']]
●Flexible arrays, not linked lists●Same operators as for strings
● a + b, a * 3, a[0], a[-1], a[1:], len(a)
●Item and slice assignment● A[0] = 98a[1:2] = ['bottles', 'of', 'beer']--> [98, 'bottles', 'of', 'beer', ['on', 'the wall']]
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
More list operations
• >>> a = range(5) # [0, 1, 2, 3, 4]>>> a.append(5) # [0, 1, 2, 3, 4, 5]>>> a.pop() # [0, 1, 2, 3, 4]5>>> a.insert(0, 5.5) # [5.5, 0, 1, 2, 3, 4]>>> a.pop(0) # [0, 1, 2, 3, 4]5.5>>> a.reverse() # [4, 3, 2, 1, 0]>>> a.sort() # [0, 1, 2, 3, 4]
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Dictionaries
●Hash tables, associative arrays● d = {"duck": "bird", "water": "liquid"}
●Lookup:● d["duck"] # --> "bird"d["back"] # raises KeyError exception
●Delete, insert, overwrite:● del d["water"]d["dirt"] = "solid"d["duck"] = "wet bird"
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
More dictionary operations
●Keys, values, items:● d.keys() --> ['duck', 'water', 'dirt']d.values() --> ['wet bird', 'liquid', 'solid']d.items() -->[('duck', 'wet bird'), ('water', 'liquid'), ('dirt', 'solid')]
●Presence check:● d.has_key('duck') --> 1d.has_key('spam') --> 0'duck' in d --> 1
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
More about dictionaries
●Values of any type, keys of many types:● {'name': 'Fred', 'age': 36, # IIRC... ('hello', 'world'): 1, 42: 'yes!', 'flag': ['red', 'white', 'blue'], }
● Keys cannot be mutable objects (like lists or dictionaries)
● Values can be anything at all● Contents are not ordered
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Variables
●No need to declare●Assign to initialize
● Use of unassigned variable raises exception
●Not typed● if friendly: greeting = 'Hello, world'else: greeting = 12 ** 2print greeting
●Everything is stored as a variable● Functions, modules, classes
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Reference semantics
• Assignment manipulates references• x = y does not make a copy of y• X = y makes x reference the object y references
• Very useful, but beware!• Example:
• >>> a = [1, 2, 3]>>> b = a>>> a.append(4)>>> print b[1, 2, 3, 4]
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Control structures
• if condition: statements[elif condition: statements][else: statements]
• while condition: statements[else: statements]
• for var in sequence: statements[else: statements]
• breakcontinue
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Structural indentation
• for i in range(20): if i % 3 == 0: print i if i % 5 == 0: print 'Bingo!' print '---'
• for (i = 0; i < 20; ++i){ if (i % 3 == 0) { printf("%d\n", i); if (i % 5 == 0) { printf("Bingo!\n"); } } printf("---\n");}
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Functions
• def name(arg1, arg2, ...): "documentation" # optional statements return # no value return expression
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Example Function
• def gcd(a, b): "Return greatest common divisor." while a != 0: a, b = b % a, a # parallel assignment return b>>> print gcd.__doc__Return greatest common divisor.>>> gcd(12, 20)4
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Classes
• class MyClass: "documentation" statementsclass MyClass(BaseClass1, BaseClass2): "documentation" statements def method(self, arg1, arg2, ...): pass classvar = 42
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Example Class
• class Stack: def __init__(self): self.items = [] def push(self, x): self.items.append(x) def pop(self): # what happens when list is empty? return self.items.pop() def empty(self): return len(self.items) == 0
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Using Classes
• Creating instances:x = Stack()
• Using an instance:x.empty() # --> 1x.push(1)x.empty() # --> 0x.push("hello!")x.pop() # --> "hello!"
• Checking instance variables:x.items # --> [1]
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
•Subclassing
• class FancyStack(Stack): """Stack with the ability to inspect inferior stack items.""" def peek(self, n): """peek(0) returns top, peek(-1) returns item below that, etc.""" size = len(self.items) assert 0 <= n < size return self.items[size-1-n]
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
More Subclassing
• class LimitedStack(FancyStack): "FancyStack with size limit." def __init__(self, limit): self.limit = limit # Call the base constructor FancyStack.__init__(self) def push(self, x): assert len(self.items) < self.limit # Call base class to do the work FancyStack.push(self, x)
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Class & Instance Variables
• class Connection: verbose = 0 def __init__(self, host): self.host = host def set_debug(self, v): # make 'verbose' an instance variable self.verbose = v def connect(self): # class or instance doesn't matter! if self.verbose: print 'connecting to', self.host ...
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Instance Variable Rules
• Use of an instance variable, search order:– Instance
– Class
– Base classes
• On assignment, always make an instance variable
• Class variables provide “defaults” for instance variables
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Class Variable Caveats
• Mutable class variables:– One copy shared by all instances
• Mutable instance variables:– Separate copy for each instance
• Can lead to surprises if you're not careful
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Careless Use of Class Variables
• >>> class Thing:... stuff = []... def addStuff(self, x):... self.stuff.append(x)...>>> t1 = Thing()>>> t2 = Thing()>>> t1.addStuff(42)>>> print t2.stuff[42]
• Probably not what you wanted!
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Modules
• Collection of definitions in foo.py file– Functions, classes, variables
• Using Modules:– import os; print os.name
– from os import name; print name
• Rename after import:– import Tkinter; Tk = Tkinter; del Tkinter
– # new in Python 2.2:import Tkinter as Tk
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Packages
• Collection of modules in a directory
• Must have __init__.py file– Provides package initialization
• May contain subpackages
• Import syntax:– import P.Q.M; print P.Q.M.foo()from P.Q import M; print M.foo()from P.Q.M import foo; print foo()
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Error Handling
• Uses exceptions, like many other languages
• Many standard exceptions provided
• Programmer can define new exceptions
• Exceptions are defined as classes
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Catching Exceptions
• try: f = open('story.txt')except IOError, e: print 'Could not open file:', eelse: print 'Once upon a time...' print f.read()
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Ensuring Cleanup Operations
• f = open('somefile.dat')try: process_file(f)finally: f.close() # always executedprint 'Done.' # executed on success only
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Raising Exceptions
• raise IndexError
• raise IndexError, 'k out of range'
• raise IndexError('k out of range')
• try: somethingexcept: print 'Oops!' raise
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
Defining Exceptions
• class ParseError(Exception): def __init__(self, lineno, offset, msg): self.lineno = lineno self.offset = offset self.message = msg def __str__(self): return '%s (line %d, character %d)' \ % (self.message, self.lineno, self.offset)def parseFile(f): ... if something_isnt_right: raise ParseError(lineno, offset, 'Found vile curly bracket!')
Slide 1 ©2002 Zope Corporation. All Rights Reserved.
• http://starship.python.net/~fdrake/