Introduction to Python

Download Report

Transcript Introduction to Python

Introduction to Python
Fred L. Drake, Jr.
[email protected]
Overview
Slide 1
•
What is Python?
•
Why use Python?
•
Compared to Other Languages
•
Basic Tutorial
©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
•
Slide 1
•
C/C++/Fortran/whatever
•
Java (using Jython or JPE)
Embeddable
©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
•
•
Slide 1
Many books, & more to come
Newsgroups: comp.lang.python,
comp.lang.python.announce
©2002 Zope Corporation. All Rights Reserved.
High-level properties
•
•
Elegant & easy to learn
•
“Executable pseudo-code”
•
Suitable as a first language
Extremely portable
•
•
Slide 1
Linux, Unix, Mac OS, PalmOS, OS/2, BeOS,
Amiga, VMS, Cray, OS/390, ...
Sorry(!): Windows, WinCE, PocketPC
©2002 Zope Corporation. All Rights Reserved.
High-level properties, cont.
•
Compiled to interpreted byte code
•
•
•
Byte code is higher-level than Java byte code,
so performance is better for most applications
Automatic memory management
•
•
Slide 1
Compilation is implicit and automatic
Reference counting
•
Predictable object destruction
•
Amortized cost for reclamation
Cycle detector for circular references
©2002 Zope Corporation. All Rights Reserved.
Safety
•
•
Even security people won't talk about
safety, why is it here?
What we mean is:
•
•
Slide 1
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
©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
•
Slide 1
SVGAlib, Mac OS, X11/Motif, MFC
•
Open source and commercial databases
•
Java (using Jython or JPE)
©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
●
Slide 1
©2002 Zope Corporation. All Rights Reserved.
And...
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
●
Slide 1
Python is for people
©2002 Zope Corporation. All Rights Reserved.
Indentation in Python
●
Indentation is used to indicate structure
●
●
●
Slide 1
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;
}
©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
•
•
Slide 1
Large library: binary data, sockets, regular
expressions, Web protocol connections
Extensions: modules can define new types
in Python, C, C++, whatever.
©2002 Zope Corporation. All Rights Reserved.
• Why use Python?
Slide 1
©2002 Zope Corporation. All Rights Reserved.
Productivity!
●
Reduced development time
●
●
Improved program maintenance
●
●
Code is extremely readable
Less training
●
Slide 1
Code is 2-10x shorter than C/C++/Java
Python is easy to learn
©2002 Zope Corporation. All Rights Reserved.
What is it used for?
Slide 1
•
Rapid prototyping
•
Web scripting
•
Ad-hoc programming
•
Steering scientific applications
•
XML processing
•
Database applications
•
GUI applications
•
Extension language
©2002 Zope Corporation. All Rights Reserved.
Who uses Python?
Slide 1
•
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)
©2002 Zope Corporation. All Rights Reserved.
Exciting applications
Slide 1
•
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
©2002 Zope Corporation. All Rights Reserved.
Typical Success Stories
•
Prototype in Python
•
First to market
•
Acquisition
•
Re-write in C++/Java
•
•
Slide 1
e-shop (now MS Commerce Server),
411 (now Yahoo! Mail)
Steering
•
Symbiosis of Python and C++ or Java
•
LANL, LLNL, ILM, Hubble Space Telescope
©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
•
•
More readable code
•
Slide 1
Important for occasional users
Easier maintenance
•
Fewer “magical” side effects
•
More modular, better for large projects
•
Better Java integration
•
Less Unix bias
©2002 Zope Corporation. All Rights Reserved.
Python vs. Tcl
•
Object oriented
•
More differentiated syntax
•
Less need for C extensions
•
Extensions can't redefine syntax
•
Slide 1
Hence fewer extension conflicts
•
Better Java integration
•
Python uses Tk as de-facto GUI standard
©2002 Zope Corporation. All Rights Reserved.
Python vs. Java
•
Code is 5-10x more concise
•
Dynamic typing
•
Much quicker development
•
Slide 1
•
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
©2002 Zope Corporation. All Rights Reserved.
Jython
•
Seamless integration with Java
•
Separate implementation
•
Implements the same language
•
Different set of standard modules
•
•
Slide 1
But lots of overlap
Differences in some “grey areas”
•
Some introspection is different
•
Command line options, etc.
©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
•
Slide 1
Pass instances back to Java
©2002 Zope Corporation. All Rights Reserved.
• Basic Tutorial
Slide 1
©2002 Zope Corporation. All Rights Reserved.
Tutorial Outline
Slide 1
•
Shell (numbers, strings, variables)
•
Lists (arrays), dictionaries (hashes)
•
Variable semantics
•
Control structures & functions
•
Classes & methods
•
Standard library
©2002 Zope Corporation. All Rights Reserved.
Interactive “Shell”
•
Slide 1
Great for:
•
Learning the language
•
Experimenting with the library
•
Testing your own modules
©2002 Zope Corporation. All Rights Reserved.
Interactive Example
Type statements or expressions at the
prompt:
●
●
Slide 1
>>> print "Hello, world"
Hello, world
>>> x = 12 ** 2
>>> x / 2
72
>>> # this is a comment
©2002 Zope Corporation. All Rights Reserved.
Numbers
•
The usual notations and operators
•
•
C-style shifting & masking
•
•
1 << 16, x & 0xff, x | 1, ~x, x ^ y
Integer division truncates
•
Slide 1
12, 3.14, 0xFF, 0377, (-1 + 2) * 3 / 4**5,
abs(x), 0 < x <= 5
1 / 2 --> 0
©2002 Zope Corporation. All Rights Reserved.
# float(1) / 2 --> 0.5
Numbers, cont.
•
Long (arbitrary precision)
•
2L ** 100 --> 1267650600228229401496703205376L
•
Starting in Python 2.2:
2 ** 100 --> 1267650600228229401496703205376L
•
Complex
•
Slide 1
1j ** 2 --> (-1+0j)
©2002 Zope Corporation. All Rights Reserved.
Strings
"
"
"
"
"
l
"
"
hel l o"
+ " wo r l d""
hel l o"
* 3
"
hel l o" [ 0]
"
hel l o" [ - 1]
"
hel l o" [ 1: 4]
"
en( " hel l o" )
5
hel l o"
< " j e l l o1"
e"
i n " hel l o"
1
" escapes: \ n et c. ,
' si ngl e quot es'
h e l l o wo r l d "
# concat enat i on
h e l l o h e l l o h e l l o# " r e p e t i t i o n
h"
# i ndexi ng
o"
# i ndexi ng ( f r om end)
el l "
# sl i ci ng
# l engt h
# c o mp a r i s o n
# sear ch
\ 033,
' ' ' t r i pl e quot es t o span
mu l t i p l e l i n e s ' ' '
r " r aw st r i ngs"
Slide 1
©2002 Zope Corporation. All Rights Reserved.
\ xf f
et c. "
Lists
●
●
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
●
Slide 1
a = [99, 'bottles of beer', ['on', 'the wall']]
A[0] = 98
a[1:2] = ['bottles', 'of', 'beer']
--> [98, 'bottles', 'of', 'beer', ['on', 'the wall']]
©2002 Zope Corporation. All Rights Reserved.
More list operations
•
Slide 1
>>>
>>>
>>>
5
>>>
>>>
5.5
>>>
>>>
a = range(5)
a.append(5)
a.pop()
# [0, 1, 2, 3, 4]
# [0, 1, 2, 3, 4, 5]
# [0, 1, 2, 3, 4]
a.insert(0, 5.5)
a.pop(0)
# [5.5, 0, 1, 2, 3, 4]
# [0, 1, 2, 3, 4]
a.reverse()
a.sort()
# [4, 3, 2, 1, 0]
# [0, 1, 2, 3, 4]
©2002 Zope Corporation. All Rights Reserved.
Dictionaries
●
Hash tables, associative arrays
●
●
Lookup:
●
●
d["duck"]
d["back"]
# --> "bird"
# raises KeyError exception
Delete, insert, overwrite:
●
Slide 1
d = {"duck": "bird", "water": "liquid"}
del d["water"]
d["dirt"] = "solid"
d["duck"] = "wet bird"
©2002 Zope Corporation. All Rights Reserved.
More dictionary operations
●
Keys, values, items:
●
●
Presence check:
●
Slide 1
d.keys() --> ['duck', 'water', 'dirt']
d.values() --> ['wet bird', 'liquid', 'solid']
d.items() -->[('duck', 'wet bird'),
('water', 'liquid'), ('dirt', 'solid')]
d.has_key('duck') --> 1
d.has_key('spam') --> 0
'duck' in d --> 1
©2002 Zope Corporation. All Rights Reserved.
More about dictionaries
●
Values of any type, keys of many types:
●
●
Slide 1
{'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
©2002 Zope Corporation. All Rights Reserved.
Variables
●
No need to declare
●
Assign to initialize
●
●
Not typed
●
●
if friendly:
greeting = 'Hello, world'
else:
greeting = 12 ** 2
print greeting
Everything is stored as a variable
●
Slide 1
Use of unassigned variable raises exception
Functions, modules, classes
©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:
•
Slide 1
>>>
>>>
>>>
>>>
[1,
a = [1, 2, 3]
b = a
a.append(4)
print b
2, 3, 4]
©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]
• break
continue
Slide 1
©2002 Zope Corporation. All Rights Reserved.
Structural indentation
•
Slide 1
for i in range(20):
if i % 3 == 0:
print i
if i % 5 == 0:
print 'Bingo!'
print '---'
©2002 Zope Corporation. All Rights Reserved.
•
for (i = 0; i < 20; ++i)
{
if (i % 3 == 0) {
printf("%d\n", i);
if (i % 5 == 0) {
printf("Bingo!\n"); }
}
printf("---\n");
}
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"
statements
class 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()
# --> 1
x.push(1)
x.empty()
# --> 0
x.push("hello!")
x.pop()
# --> "hello!"
•
Checking instance variables:
x.items
Slide 1
©2002 Zope Corporation. All Rights Reserved.
# --> [1]
•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:', e
else:
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 executed
print '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:
something
except:
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/
Slide 1
©2002 Zope Corporation. All Rights Reserved.