Presentation is loading. Please wait.

Presentation is loading. Please wait.

National Aeronautics and Space Administration www.nasa.gov 1 Python Overview.

Similar presentations


Presentation on theme: "National Aeronautics and Space Administration www.nasa.gov 1 Python Overview."— Presentation transcript:

1 National Aeronautics and Space Administration www.nasa.gov 1 Python Overview

2 National Aeronautics and Space Administration www.nasa.gov 2 What is Python Python is a scripting language with a unique, but clear, syntax Python is widely used in science and engineering Initially developed in early 1990’s, current version 2.4 Licensing –Python’s license is a very open –Code can be distributed, along with the python interpreter, freely or in commercial projects –No requirement that source code be released (unlike GPL)

3 National Aeronautics and Space Administration www.nasa.gov 3 Pros and Cons of Python Pros –It’s clean, easy to pick up –It’s been around for a while, and has a wide user base –Theres an extensive set of math and scientific libraries for it –It can be used with MATLAB-like functionality –It’s implementation is almost identical on a wide variety of platforms –It's free (as in beer, and as in speech) –It’s excellent at manipulating text Cons –Python's I/O is fast, and its programming constructs are very easy and robust, but for number crunching pure Python will be much slower than C or Fortran –Fortunately, it can be tied to C and Fortran with wrappers, making it a good way to gui compiled languages together SWIG (for C), F2PY (for Fortran), Pyrex (turn Python code into C) –Some Python modules (Numeric Python, Scientific Python) already wrap a substantial number of useful computationally intensive C and Fortran routines Easier to write and maintainFaster execution Pure PythonPython with C/Fortran Calls (SWIG,F2PY,Pyrex,etc) Pure C/Fortran

4 National Aeronautics and Space Administration www.nasa.gov 4 Python Features Syntax –White-space is significant The extent of a block (if, for, etc) is defined by its indentation No set number of spaces or tabs, but must be consistent for a given block –Case sensitive All syntax and string comparisons (by default) are case sensitive –Line-Continuation Python lines do not end with ; To continue a line, end one line with a \ and continue onto the next line of code (indentation isnt required, but its clearer) If a parentheses or bracket is currently open, the \ isn’t necessary –Comments # begin comments in python. They continue until the end of the line

5 National Aeronautics and Space Administration www.nasa.gov 5 Python Features (Continued) Object oriented –Everything is an object, including functions –Inheritence Objects can inherit the properties and capabilities of other objects –Polymorphism Routines don’t care what type of data is passed to them. Its up to them to handle it. Exception handling –Exceptions can be cleanly taken care of to avoid bad situations like divide-by-zero –Custom exceptions can be designed Many useful utilities in standard libraries (modules) and many more useful utilities in 3rd party, open-source modules Extensions can be written in C and C++, and support for linking to Fortran exists. –Execution speed of C/Fortran, development ease of Python

6 National Aeronautics and Space Administration www.nasa.gov 6 Python Features (Continued) Introspection –Easily see what objects can do, including help information –Documentation strings (encapsulated by “””) provide hooks for automatic documentation generators –The pydoc utility will automatically generate HTML documentation for Python files Things to watch out for –There are no constant parameters, everything can be changed –Scope rules can be tricky at first –Be consistent with indentation, don’t mix tabs and spaces (use spaces)

7 National Aeronautics and Space Administration www.nasa.gov 7 Running Python –Python needs an interpreter to run Most Unix systems, including OS X, come with an interpreter For Windows and OS X, I like the free ActivePython interpreter from http://www.activestate.com, but there are many others http://www.activestate.com –When invoked with a script file name, python just runs the contents of the script. If run without any arguments, python starts up an interactive shell. python script invocation python interactive shell –Most examples in this presentation show Python in the intereactive shell, but they’ll work just as well in a file, without the preceding >>> and... prompts on each line $ python helloworld.py hello, world! $ $ python ActivePython 2.4.3 Build 11 Type “help”, “copyright”, “credits” or “license” for more infromation. >>> print ‘hello, world!’ hello, world! >>>

8 National Aeronautics and Space Administration www.nasa.gov 8 Running Python (Continued) –The python interactive shell can, in its most basic form, be used as a calculator –The interactive shell does not need print statements, it will automatically print the result of the previous command –The interactive shell’s prompt is >>> –If the interactive shell is expecting an indented block, the prompt will change to... $ python ActivePython 2.4.3 Build 11 Type "help", "copyright", "credits" or "license" for more infromation. >>> from math import * >>> 5+5 10 >>> sqrt(5) 2.2360679774997898 $ python ActivePython 2.4.3 Build 11 Type "help", "copyright", "credits" or "license" for more infromation. >>> for i in range(5):... print i, 0 1 2 3 4

9 National Aeronautics and Space Administration www.nasa.gov 9 Numeric Types int, float, long, complex –The type of a literal is determined as follows An unadorned integer literal is stored as a plain integer An integer literal with a L or l suffix is stored as a long integer (use L) A literal containing a decimal point is stored as C doubles The real and imaginary components of a complex number are stored as C doubles

10 National Aeronautics and Space Administration www.nasa.gov 10 Boolean Types Boolean –What is True and what is False? The keywords True and False are self explanatory The following are false: –Numbers which are 0 –Empty strings ("") –Empty lists ([ ]), tuples (()), etc –The value None Everything else is True Prior to Python 2.3, True and False didn’t exist, and were usually replaced by 1 and 0 –Comparisons Same as in C (, >=, ==, !=) Work as expected on numeric types For strings, these essentially evaluate to alphabetical order Numeric types always evaluate as being less than strings

11 National Aeronautics and Space Administration www.nasa.gov 11 Boolean Types (Continued) –Boolean Operators and –Evaluating from left to right, returns the first False value –If all values are True, returns the last value or –Like and, evaluates from left to right, but returns the first True value –If all values are False, returns the last value –Keep cheap computations towards the left of expensive ones not not x is True if x is False in The “membership test” a in myList is True if any element in myList is equal to a >>> ‘a’ and ‘b’ and ‘c’ ‘c’ >>> ‘a’ and 0 and ‘c’ 0 >>> ‘a’ or ‘b’ or ‘c’ ‘a’ >>> ‘’ or 0 or ‘c’ ‘c’

12 National Aeronautics and Space Administration www.nasa.gov 12 Strings Strings are defined with single or double quotes (‘ or “) –Which you use doesn’t really matter as long as your consistent –Only “ to close “ and only ‘ to close ‘ Once created strings are immutable –You cannot change characters within a string –Just reassign the string to a new value String operators –+ (Exponentiation): “One” + “Two” = “OneTwo” –* (Repetition): “Test” * 3 = “TestTestTest” Escape sequences (some of them anyway) –\n line feed (native to unix and OS X) –\r carriage return (native to MacOS) –\r\n carriage return/ line feed (Windows) –Python works with \n on all platforms (Cross-platform solution to line endings is the linesep variable in module os) –\t tab –\’ single quote (unnecessary if string is in double quotes) –\” double quote (unnecessary if string is in single quotes) –\\ backslash

13 National Aeronautics and Space Administration www.nasa.gov 13 Strings (Continued) Common String Methods a.count(sub[,start[,end]]) Return the number of occurrences of substring sub in a[start:end] a.find(sub[,start[,end]]) Return the lowest index of a string where sub is found, in a[start:end] Return -1 if sub is not found a.index(sub[,start[,end]]) Like find(), but will raise a ValueError instead of returning -1 if sub is not found a.isalpha() True if all the characters in a are alphabetic a.isdigit() True if all the characters in a are digits a.isalnum() True if all the characters in a are alphanumeric

14 National Aeronautics and Space Administration www.nasa.gov 14 Strings (Continued) a.lower(), a.upper(), a.swapcase() Convert a to lower case, upper case, or reverse case, respectively a.split([sep,[maxsplit]]) Returns a list of strings obtained by using sep as a delimiter (default is whitespace). If maxsplit is specified, string will be split up to maxsplit times a.strip([chars]) Removes leading and trailing whitespace, unless chars is specified If chars is specified, removes any character found in the string chars Much greater search and substitution capabilities are available through the regular expressions module (re)

15 National Aeronautics and Space Administration www.nasa.gov 15 Strings (Continued) Strings can be formatted similar to the functionality of sprintf() in C stringExpression % (formatList) stringExpression is a string populated with formatting operators formatList is a value, tuple, or dictionary of values to replace the formatting operators (parentheses mandatory for tuples, braces mandatory for dictionaries) Formatting Operators –%i integer –%d decimal integer –%f floating point number –%u unsigned integer –%x hexadecimal integer –%X hexadecimal integer in uppercase letters –%o octal integer –%e floating point number in scientific notation –%E floating point number in scientific notation (uppercase E) –%s string or any object with the __str__ method –%c a single character –% a literal percent sign

16 National Aeronautics and Space Administration www.nasa.gov 16 Strings (Continued) More complex string formatting can be done Conversions must by specified as follows –% character, the start of the specifier –The mapping key, if a format list is a dictionary, contained in parentheses –Conversion flag (optional, see below) –Minimum Field Width (optional) –A. followed by the number of decimal places in the field –The conversion type Conversion flags –0 pad the result with zeros –- left-justify the result (overrides 0) – (space). Leave an extra blank before a positive number –+ Always precede the result with a + or - sign. (Overrides space) >>> ‘%s has %i main engines’ % (‘Shuttle’, 3) ‘Shuttle has 3 main engines’ >>> >>> ‘%9.6f’ % 12.2 # Format 12.2 with 6 decimal places and a field width of at least 9 ‘12.200000’ >>> ‘%6.1f’ % 12.2 # Format 12.2 with 1 decimal place and a field width of at least 6 ‘ 12.2’

17 National Aeronautics and Space Administration www.nasa.gov 17 Lists –List are one of Python's array-like types –Created with square brackets –May contain multiple variable types –Indexing The first element of a list is at index 0 Indices can be negative –Slicing Lists may be ‘sliced’ similar to Fortran90 and MATLAB arrays (slices return lists) Think of slices as returning [from : up to but not including] >>> integerList = [1, 2, 3, 4] >>> myList = [1, 2, 3.7, ‘a’, ‘b’] >>> print myList[-1] b >>> print myList[0:3] [1, 2, 3.7] >>> print myList[2:3] [3.7] >>> print myList[-2:] [‘a’,’b’]

18 National Aeronautics and Space Administration www.nasa.gov 18 List Methods –If you’re going to build a list with a number of append or insert statements, let python know that the item you’re working on is a list >>> listOfNames.append('Bob') Traceback (most recent call last): File, line 1 in ? NameError: name ‘listOfNames’ is not defined >>> listOfNames = [] >>> listOfNames.append(“Bob”) >>> print listOfNames [‘Bob’]

19 National Aeronautics and Space Administration www.nasa.gov 19 List Comprehensions –List comprehensions allow a concise way to modify a list –“Give me ___ for each item in the list (if ___ is true)” –Examples Give me the square of each number in a list Give me the index of each number in a list that is even Given a list of lines of Fortran90 code, return non-commented lines >>> integerList = [1, 2, 3, 4] >>> squareList = [x**2 for x in integerList] >>> print squareList [1, 4, 9, 16] >>> numberList = [1,2,3,5,7,8,10,12] >>> evenList = [i for i in range(len(numberList)) if numberList[i] % 2 == 0] >>> print evenList [1, 5, 6, 7] >>> codeLines = [line for line in fortranLines if line.strip()[0] != '!']

20 National Aeronautics and Space Administration www.nasa.gov 20 List Sorting The.sort() method of a list sorts its items in place. It returns None. For strings and numeric types, sorting is extremely straightforward But what if we’re sorting objects based on some property of that object? e.g. sorting launch vehicles based on payload capability To get around this types contain a special function named __cmp__(self,other) –Returns a negative integer if self < other –Returns a positive integer if self > other –Returns 0 if self == other For the launch vehicle example we may have __cmp__(self, other): if self.payload < other.payload: return -1 elif self.payload > other.payload: return 1 return 0 >>> numberList = [7, 5, 8, 200, 15, 1, 6] >>> numberList.sort() >>> print numberList [1, 5, 6, 7, 8, 15, 200]

21 National Aeronautics and Space Administration www.nasa.gov 21 Dictionaries Dictionaries are similar to lists except they are unordered and elements are referenced by keys instead of by indices Dictionaries are defined using curly braces, and elements are accessed using square brackets Python keeps the numbers in an arbitrary but non-random order that varies from platform to platform - never assume you know the storage order Dictionaries are mutable, values of elements can be reassigned keys and values are returned through the dictionary’s keys() and values() methods lists returned by keys() and values() don’t necessarily have the same order >>> numbers = {‘Bob’: 1203, ‘Cletus’: 2614, ‘Wolfgang’: 7671} >>> print numbers {‘Wolfgang’: 7671, ‘Bob’: 1213, ‘Cletus’: 2614} >>> numbers[‘Cletus’] = 4444 >>> print numbers[‘Cletus’] 4444 >>> print numbers.keys() ['Wolfgang', 'Bob', 'Cletus'] >>> print numbers.values() [7671, 1203, 2614]

22 National Aeronautics and Space Administration www.nasa.gov 22 Tuples A tuple is an immutable sequence of values separated by commas, optionally contained in parentheses A tuple with zero items is created with an empty set of parentheses A tuple with one item is created by ending a list of values with a comma Tuple elements are accessed using square brackets Like lists, tuples can be nested, and can contain multiple variable types Multiple assignments of variables can be made to elements of a tuple >>> myTuple = 1,’two’,’three’,4 >>> print myTuple (1, ‘two’, ‘three’, 4) >>> print myTuple[0] >>> two, three = myTuple[1:3] >>> print two ‘two’ >>> print three ‘three’

23 National Aeronautics and Space Administration www.nasa.gov 23 Files Python has extensive support for reading binary and ASCII/Unicode files open(filepath [,mode][,buffering]) open returns a file object. It requires a file path. It doesn’t have to be a full path. File name is sufficient for files in the current working directory. Raises an IOError if unsuccessful. For text files, mode is one of the following –‘r’ - read-only (default) –‘w’ - write –‘a’ - append Here are some of the more useful file methods, especially for text files f.close() Flush buffer and close file f f.read([size]) Return the entire file contents (up to size bytes) as a string f.readline([size]) Return next line in f as a string (includes end-of-line character) f.readlines([sizehint]) Return a list of all lines in f (includeng end-of-line characters) f.write(str) Write string str to f, equivalent to print >> f, str,

24 National Aeronautics and Space Administration www.nasa.gov 24 Files (Continued) –A list comprehension is a good way to remove end-of-line characters –Binary files can be read and written, just append ‘b’ to the file mode Some more file methods that work for all files, but are more useful for binary files f.tell() Returns the file objects current position in the file as an integer number of bytes starting from the beginning f.seek(offset[,whence]) Set the file’s current position >>> f = open(‘myfile.txt’,’r’) >>> lines = f.readlines() >>> f.close() >>> # At this point, lines is a list of lines including line endings >>> lines = [line[:-1] for line in lines] # remove last char from each line >>> # Now lines doesnt contain line endings >>> f = open(‘myfile.bin’,’rb’)

25 National Aeronautics and Space Administration www.nasa.gov 25 Scope Scope defines where variables are accessible –Innermost scope is searched first The current block, followed by any blocks which contain it, and then its enclosing function or class –Middle scope is searched next If a variable wasn’t found in the innermost scope, python looks for it in the global variables of the current module –Outermost scope is searched last If python still hasn’t found the variable, it searches the namespace of builtin Python names –Local scope The current function or class, or if done outside either of those, the module’s scope (global scope)

26 National Aeronautics and Space Administration www.nasa.gov 26 Scope Example Consider the following example Why was the result 26 instead of 13? –x = 24 is defined in the global namespace (outside everything) –Assigning x=11 in bar() assigned it to bar’s namespace, the value of x in the global namespace was unchanged –To force bar to modify the global variable x, tell it that x is a global >>> x = 24 >>> def foo():... y = 2... print x+y... >>> def bar():... x=11... foo()... >>> bar() 26 >>> def bar():... global x... x = 11... foo()

27 National Aeronautics and Space Administration www.nasa.gov 27 Constructs Built-In Statements and Functions If Blocks For Loops While Loops Exception Handling Functions (Methods) Lamda Functions Classes Modules

28 National Aeronautics and Space Administration www.nasa.gov 28 Built-in Statements and Functions print [ >> filelikeObject] expression –Prints expression to the file-like object –(expression can be a comma separated list, aka a tuple) –If no file-like object is specified, then sys.stdout is used –Appends \n to the end unless statement ends with a comma pass –Do nothing –Blocks must contain at least one executable statement, but sometimes there isnt anything to be done (in a waiting while loop for instance) del(a) –Delete a variable (or slice of an array) return x,y,z –Returns values from a function >>> print ‘hello, world!’ hello, world! >>> for i in [1,2,3]:... print i,... 1 2 3

29 National Aeronautics and Space Administration www.nasa.gov 29 Built-in Statements and Functions dir(a) –Print attributes and methods of a range([start,] stop[, step]) –Returns every step’th integer from start (default = 0) to (but not including) stop len(a) –Simplistically, it returns the length of a string, list, tuple, etc –Techinically, it returns the value from an objects __len__ method assert expression –If expression is not True, and python was not started in optimized mode (python -O), will raise an AssertionError (useful for debugging)

30 National Aeronautics and Space Administration www.nasa.gov 30 if, elif, else If blocks do what they do in other languages, evaluate if a given condition is True If blocks in python, like all other construct blocks, begin with a colon after the if statement, and continue until indentation ends elif is used in place of elseif to reduce the character count of lines Python has no Select Case statement, use if...elif statements instead >>> x = 15 >>> if x < 10:... print ‘x is less than 10’... elif x > 20:... print ‘x is greater than 20’... else:... print ‘x must be between 10 and 20’... x must be between 10 and 20 >>> print ‘done’ done

31 National Aeronautics and Space Administration www.nasa.gov 31 For Loops for loops are somewhat unique in Python, they iterate through a list Needless to say, this would be horrible for looping through hundreds of things The range function solves this by returning a list of integers range([start,] stop[, step]) –Returns every step’th integer from start (default = 0) to (but not including) stop For example, the previous loop has the equivalent: And its possible to do negative steps >>> for i in [0, 1, 2, 3]:... print i,... 0 1 2 3 >>> for i in range(4):... print i,... 0 1 2 3 >>> for i in range(4,0,-1):... print i,... 4 3 2 1

32 National Aeronautics and Space Administration www.nasa.gov 32 For Loops (Continued) There are a few ways to iterate through a list in Python –Iterate through each item of the list –Iterate through the indices of the list I usually prefer to iterate through each item when possible because the code is more concise However, the list element cannot be changed this way To get around this, iterate using the list indices >>> listOfNames = [‘Bob’,’Tom’,’Jerry’,’Cletus’]] >>> for name in listOfNames:... print name,... Bob Tom Jerry Cletus >>> listOfNames = [‘Bob’,’Tom’,’Jerry’,’Cletus’]] >>> for name in listOfNames:... name = name.upper()... print name,... BOB TOM JERRY CLETUS >>> print listOfNames [‘Bob’,’Tom’,’Jerry’,’Cletus’]

33 National Aeronautics and Space Administration www.nasa.gov 33 For Loops (Continued) Iterate over list indices if you want to modify the elements in the list This is when the len and range functions are especially useful else statements can be added to for loops –Evaluated once the list is exhausted Other statements pertaining to for loops –break Leave the loop without executing the loops else clause –continue Proceed directly to the top of the loop and continue with the next item >>> listOfNames = [‘Bob’,’Tom’,’Jerry’,’Cletus’] >>> for i in range(len(listOfNames)):... listOfNames[i] = listOfNames[i].upper()... print listOfNames[i],... BOB TOM JERRY CLETUS >>> print listOfNames [‘BOB’,’TOM’,’JERRY’,’CLETUS’]

34 National Aeronautics and Space Administration www.nasa.gov 34 While Loops Repeatedly execute a code block while a condition is True else statements can be added to while loops –After the condition is False Other statements pertaining to while loops –break Leave the loop without executing the loops else clause –continue Immediately go to the top of the loop and re-test the condition –pass pass does nothing in Python, its useful in while loops to implement a pause or wait statement >>> i = 0 >>> while i < 100:... i = i + 1... >>> print i 100

35 National Aeronautics and Space Administration www.nasa.gov 35 Exception Handling –Python supports handling of exceptions through try/except/else –Allow graceful handling of errors and branching based upon error conditions –Must have a try clause and at least one except clause –The except clause man specify the class of error handled by that except clause, and optionally an instance of that exception –Theres an optional else clause that is executed if no exceptions are raised try: executable statements... except [ExceptionClass [,exception instance]]: executable statements if exception is raised else: exectuable statements if no exception is raised –For instance, to cleanly open a file >>> try:... f = open(filename, ’w’)... except IOError, e:... print 'Encountered an error in accessing ' + filename... print e... >>> print ‘done’

36 National Aeronautics and Space Administration www.nasa.gov 36 Exception Handling (Continued) –If Python encounters an unhandled exception, it will print a traceback to standard output, showing the file and line number of each related call up until the error was encountered –As you might expect, its also possible to raise exceptions in your own subroutines using the raise statement –As a basic example, raise a ValueError if x is not an even number –The type of error raised is left to the programmer, although its probably good practice to use IOError for IO related errors, ValueError for numeric value problems, IndexError for list index errors, etc –If none of the built-in error types suite you, you can create your own error class that inherits from Exception >>> x = 3 >>> if x % 2 != 0:... raise ValueError('x is not an even number')... Traceback (most recent call last): File ' ', line 2, in ? ValueError: x is not an even number >>>

37 National Aeronautics and Space Administration www.nasa.gov 37 Methods/Functions –Python functions have the following syntax def name([argList],[*args],[**kwargs]): """ Documentation String """ executable statements [return (returned values list)] –Arguments Functions can have 0 or more arguments An argument prefixed with * is a variable-length tuple of arguments. An argument prefixed with ** is a variable-length dictionary of key/argument pairs. A maximum of one tuple argument list and one dictionary argument list may be specified, and they must be the last arguments Arguments don’t have a specified type, its up to the programmer to verify that the proper types are handled –Default argument values can be specified in the argument list def payload(vehicle, alt, inc = 28.5): –Arguments can be named in the function call. They may be in any order, but once an argument is named, all proceding arguments must be named as well print payload(‘STS’, 400.0, 51.6) print payload(‘STS’, inc = 51.6, alt = 400.0)

38 National Aeronautics and Space Administration www.nasa.gov 38 Methods/Functions (Continued) –Python functions can have zero or more return values, returned as a tuple –Functions are objects...so they can be passed to other functions just like other objects –Python supports anonymous functions (called lambda functions) –Lamda functions are short, one line functions that are only useful in the scope of their containing function >>> def divide(a,b):... """ Returns a/b, and the remainder of a/b """... return a//b, a%b... >>> result, remainder = divide(a,b) print result, remainder 1 3 >>> def RK4(y, t, h, f):... """ Runge-Kutta, with user-defined derivative function (f) """ >>> square = lambda x: x**2 >>> print square(8) 64

39 National Aeronautics and Space Administration www.nasa.gov 39 Classes Classes allow complex objects to be represented as a single entity Classes contain attributes, which can be static, and functions Class Definitions class Name([DerivedFromClasses]): """ Documentation String """ static variable definitions, function definitions Class Constructors –Instances of a class are created with a constructor, which looks somewhat like a function in that it can take arguments used to define the instance clientName = Name("Bob Smith") –Variable names may be specified in class constructors as they are in functions Attributes –Attributes may be static, applying to the class as a whole, or instance attributes. Static, or ‘class’ variables are defined in the scope of the class –Static attributes may be accessed through the class, or an instance of the class, but if there is an instance variable of the same name as a static (class) variable, the instance variable takes precedence. –Instance variables are defined as members of self within class methods –Private attributes don’t exist. By convention, if a class contains an attribute that begins with a single underscore, that attribute is intended to be private

40 National Aeronautics and Space Administration www.nasa.gov 40 Classes Class Functions –Function definitions within a class are similar to normal Python function definitions, except the first argument of the function definition is self, a reference to the calling instance of the class. –Classes can contain “magic” functions, surrounded by double underscores, that hold special meanings in Python –The special function __init__(self, [args]) is called when the class is created. All arguments after self are those passed from the class constructor –__init__ is used to initialize a default state of the class instance being created >>> class Name:... """ Class for the name of a person """... def init(self, first, last = '', suffix = ''):... self.first = first.split()[0]... try:... self.last = first.split()[1]... except IndexError:... self.last = last... try:... self.suffix = first.split()[2]... except IndexError:... self.suffix = suffix... >>>

41 National Aeronautics and Space Administration www.nasa.gov 41 Classes >>> class Vector3D:... def init(self, x, y, z=0.0):... self.x = x... self.y = y... self.z = z... def magnitude(self):... from math import sqrt # need sqrt function from the math module... return sqrt(self.x**2 + self.y**2 + self.z**2)... >>> radius = Vector3D(3.0,4.0,5.0) # The Vector3D constructor >>> print radius.magnitude() # Radius is an implicit argument to magnitude() 7.0710678118654755 Example 1: A 3D Vector Class –Vector3D does not derive from any other class –The init function takes up to 3 arguments –The third argument (z) is optional, defaulting to 0.0 –Vector3D has 3 instance attributes (x,y,z) and no static attributes –The magnitude function returns the length of the vector

42 National Aeronautics and Space Administration www.nasa.gov 42 Classes >>> class MyClass:... i = 5 # i is static, an attribute of MyClass... def __init__(self,i):... self.i = i # Now I’ve overridden the instance’s value of i... self.j = i**2 # instance’s attribute j is the square of i... >>> a = MyClass(7) # The class constructor and its 1 argument (i) >>> >>> print a.i, MyClass.i, a.j 7 5 49 >>> print MyClass.j # This will fail Traceback (most recent call last):... AttributeError: class MyClass has no attribute ‘j Example 2: Static and instance attributes –MyClass has one static attribute, i –Each instance of MyClass has 2 attributes, i and j –Yes, it’s confusing that a class can have static and instance attributes of the same name. I wouldn’t recommend it in practice –The reference to MyClass.j will fail because that is only an attribute of instances of MyClass, not a static property of MyClass itself.

43 National Aeronautics and Space Administration www.nasa.gov 43 Classes (special functions and operator overloading) Classes can contain a number of special attributes and methods, surrounded by double underscores, that provide access to underlying information, and allow for operator overloading Some of the special methods are: __cmp__(self, other) Used for comparisons between objects that are inherently non-numeric and non- alphabetic. Return a negative integer if self is considered less than other, a positive integer if self is considered greater other, and zero if self is considered to be equal to other. Allows for sorting of custom types. __str__(self) Returns the string representation of this instance __del__(self) Called when this instance is about to be destroyed __init__(self [,args]) Called when an instance is created. All arguments following self are those that are passed to the class constructor expression __add__(self, other), __sub__(self,other), __mul__(self,other), __mod__(self,other) Used to overload arithmetic operators (+, -, *, %, etc) __call__(self[,args]) The value returned when the instance self is called like a function

44 National Aeronautics and Space Administration www.nasa.gov 44 Modules Modules are Python’s way of passing around structures and constructs –Functionally, modules are like libraries –Syntactically, modules are just script files Importing Modules (several methods) –Import all of a module’s contents with explicit naming import sys Import’s all attributes, functions, and classes from sys To access things from sys, must precede the attribute, class, or function name with module name sys.exit(0) # Exit script with return status of 0 –Import all of a module’s contents with implicit naming from sys import * Import’s all attributes, functions, and classes from sys Don’t precede attribute, class, or function name with module name exit(0) # Exit script with return status of 0

45 National Aeronautics and Space Administration www.nasa.gov 45 Modules (Continued) Importing Modules (continued) –Import only specific components from the module with implicit naming from sys import exit, argv Imports only the listed components Don’t precede names with module name exit(0) # Exit script with return status of 0 –Import only specific components from the module with new names implicit naming from sys import exit, argv as arguments Imports only the listed components, referenced by the name after the as keyword Don’t precede names with module name print arguments[-1] # Print the last command line argument Python compiles modules to an intermediate byte code files when they are first imported –Saves byte code in a file with.pyc extension –Only decreases loading time, not execution time. –Python detects changes in.py file and will automatically regenerate.pyc file as necessary

46 National Aeronautics and Space Administration www.nasa.gov 46 Modules (Continued) A module’s global variables are not imported if they are defined when surrounded by double-underscores, unless specifically requested from mymodule import __var__ Import statements can be put anywhere, exception handling comes in handy here try: import wx except: print ‘Encountered an error while importing wx’ sys.exit(0) A module’s executable code should appear after all class and function definitions If you’re importing a module, you probably don’t want any executable code You can put in an if statement that will only run code if the module/script is invoked directly from the command line if __name__ == '__main__': testModule() –The __name__ attribute of a module is set to ‘__main__’ if it is invoked directly from the command line

47 National Aeronautics and Space Administration www.nasa.gov 47 Modules (Example) Given the following code, saved as longdivision.py in the current working directory We can use it from the interactive shell or from the command line Note how the dir() built-in function indicates that __author__ and __date__ were not imported. This would allow me to define an __author__ and __date__ for the calling module without a naming conflict >>> from longdivision import * >>> dir() ['__builtins__', '__doc__', '__name__', 'divide'] >>> divide(11,7) (1, 4)

48 National Aeronautics and Space Administration www.nasa.gov 48 Useful Built-In Modules General system (sys) exit(0) Exit the program, providing a return status argv List of command line arguments Script file name is always argv[0] More elaborate command-line argument processing available with getopt or optparse Operating System (os) system(command) spawn a subprocess returns exit status of command popen spawn a subprocess and return pipes for communication (such as stdout) getcwd Return current working dirrectory chdir(path) change the current working directory to path

49 National Aeronautics and Space Administration www.nasa.gov 49 Useful Built-In Modules (continued) C-standard math functions (math) Command-line Arguments (getopt or optparse) XML Parsing and Writing (xml.dom, xml.dom.minidom, xml.sax) Basic GUI Stuff (Tkinter, tkFileDialog) import tkFileDialog import Tkinter root = Tkinter.Tk() root.withdraw() filename = tkFileDialog.askopenfilename(parent=root,filetypes=[('Python Source','.py')])

50 National Aeronautics and Space Administration www.nasa.gov 50 Useful Built-In Modules (regular expressions) Regular Expressions (re) –Search strings for regular expressions, replace regular expressions, etc –Very powerful capability, entire books written about regular expressions –Some common regular expressions \s whitespace $ end of string. any character \. period + one or more of the previous character * zero or more of the previous character –Search for a dot (\.) followed by one or more of any character (.+) followed by the end of a string (aka, a file suffix) –Note suffixMatch is not ‘None’, therefore it found a file suffix (and is True) –Can use parentheses to capture what was matched >>> import re >>> reSuffix = re.compile("\..+$") >>> suffixMatch = reSuffix.search("filename.txt") >>> print suffixMatch >>> reSuffix = re.compile("\.(.+)$") # ( ) used to capture the file suffix >>> suffixMatch = reSuffix.search("filename.txt") >>> print suffixMatch.groups()[0] # groups method returns tuple of found groups txt

51 National Aeronautics and Space Administration www.nasa.gov 51 The Global Module Index Theres a high probability that theres a simpler way to do what you want to do, already implemented in a module The global module index has extensive documentation on every module that comes standard with Python http://docs.python.org/modindex.html

52 National Aeronautics and Space Administration www.nasa.gov 52 Third-Party Modules Numpy –Fast, Matlab-like array interfaces wxPython –Cross-platform GUI creation –Native look and feel –MANY widgets to choose from Scipy –optimization, plotting,statistical functions, genetic algorithms, interpolation, linear algebra, FFT, sparse matrices, etc Pylab (Matlab-like plot generation) –Matlab syntax functions and fancy plots Vpython –Visual Python, simple 3D graphics PyOpenGL –Python interface to OpenGL, much more elaborate than Vpython

53 National Aeronautics and Space Administration www.nasa.gov 53 Resources Within Python –help() Enters help mode within the interpreter –dir(object) Prints attributes and methods of object –object.__doc__ The object’s docmentation string Online –Documentation - http://www.python.org/doc/ http://www.python.org/doc/ –Global Module Index - http://docs.python.org/modindex.htmlhttp://docs.python.org/modindex.html –Dive Into Python - http://diveintopython.org/http://diveintopython.org/ –Official Coding Conventions - http://www.python.org/dev/peps/pep-0008/http://www.python.org/dev/peps/pep-0008/ Local documentation –pydoc Can automatically generate documentation for your code, if you are consistent with docstrings If started with the -g argument, will start a web server on your local machine and display HTML documentation of all locally installed modules


Download ppt "National Aeronautics and Space Administration www.nasa.gov 1 Python Overview."

Similar presentations


Ads by Google