Äîêóìåíò âçÿò èç êýøà ïîèñêîâîé ìàøèíû. Àäðåñ îðèãèíàëüíîãî äîêóìåíòà : http://www.stsci.edu/hst/training/events/Python/class3.pdf
Äàòà èçìåíåíèÿ: Wed Jun 15 22:47:09 2005
Äàòà èíäåêñèðîâàíèÿ: Sun Dec 23 00:36:56 2007
Êîäèðîâêà:

Ïîèñêîâûå ñëîâà: ngc 253
STSCI Python Introduction

Class 3 Jim Hare

Today's Agenda
· · · · · · Functions Passing Arguments to Modules File I/O User Defined Objects Variable Scopes System Commands and Controls

1


Functions
· Function template · Consists of def statement, parameters and return def test1(x,y,j=`testcase1') j=`testcase1' is the default · Example update_default_db.py

Function Calls
· test1(2,3,'testcase2') # ordered call · test1(j=`testcase2', y= 3, x=2) # no order · test1(2,3) # this time j is the default `testcase1'

2


Passing Arguments
· __main__ is the name of the originating or first module run in the current execution of python def run(database, #database account='sogsspss'): #account os.system('printf "sp_defaultdb %s,%s\\ngo" | isql' % (account,database)) os.system('printf "select db_name()\\ngo" | isql') return None

Passing Arguments ­ if __name__==`__main__':
if __name__ == '__main__': if len(sys.argv) != 3: print " Error in arguments try again." sys.exit() database = string.lower(sys.argv[1]) account = sys.argv[2] run(database,account)

3


Functions Returning Values
def splitonperiod(inString): # is a string import string stringList = string.split(inString,'.') ... test = 1 return test,stringList aString = "md.spring.2003.STSCI.EDU" status,varList = splitonperiod(aString) print aString [`md','spring','2003','STSCI','EDU']

Namespace
# file : div.py def divide(a,b): q=a/b r = a ­ q*b return (q,r)

4


Namespace ­ cont.
import div a,b = div.divide(2305,29) import div as foo a,b = foo.divide(2305,29) from div import divide a,b = divide(2305,29) from div import * # all in current namespace

Modules ­ dir()
import string dir(string) # all modules have dir function [`__builtins__','__doc__','__file__', '__name__','_idmap','_idmapL','_lower', `_swapcase','_upper','atof','atof_error', `atoi','atoi_error','atol','atol_error', 'capitalize','capwords','center','count', `digits','expandtabs','find',...

5


Raw Input Command
first = raw_input(`Type your first name: `) mid = raw_input(`Type your middle name: `) last = raw_input(`Type your last name: `) print "Your full name is %s %s %s" \ % (first,mid,last) · Example: myName.py

Files
· myFile = open(`build_id.data','r') · File modes are: `r', `w', or "a". `b' following means binary ie. `rb' · Updates `r+' or `w+', can perform both input and output, as long as output operations flush their data before subsequent input operations ie. f.flush()

6


File Methods - Read
· F.read - Reads at most n bytes · F.readline() - Reads a single line of input · F.readlines() - Reads all the lines and returns a list. myList = myFile.readlines()

File Methods - Write
· F.write(S) · F.writelines(L) - Writes string S - Writes all strings in List L

7


File Methods
· F.close() - closes the file F · F.tell() - returns the file pointer · F.seek(offset [,where]) ­ seek to new file position · F.isatty() - 1 if F is interactive terminal · F.flush() - Flushes output buffers · F.truncate([size]) - truncates to size bytes · F.fileno() - integer descriptor

File Attributes
· F.closed - Boolean 0 = open, 1=closed · F.mode - I/O mode of file · F.name - name of file or source · F.softspace - indicator of whether a space character needs to be printed before another value when using the print statement.

8


Standard Input, Output, and Error
· import sys - to get access to Standard I/O files · sys.stdin - Standard Input · sys.stdout - Standard Output · sys.stderr - Standard Error

Object Oriented Programming Concepts
· Class ­ an object/statement defining inherited members and methods · Instance ­ object created from a class. · Member ­ an attribute of an object, the data bound to the object · Method ­ function attribute of an object · Self ­ the name given to the implied instance object in methods.

9


Class -- Example
Object MyAccount Class PhoneDir

Name AccountID Balance Insert Add Balance

Paul Lee 123.45.678 $10.00 withdraw deposit balance

Instances of Class Account

Object YourAccount

Jane Doe 234.56.789 $1000000.00 withdraw deposit balance

Object -- Example
Object MyAccount Class Account

Name AccountID Balance Withdraw Deposit Balance

Paul Lee 123.45.678 $10.00 withdraw deposit balance

Instances of Class Account

Object YourAccount

Jane Doe 234.56.789 $1000000.00 withdraw deposit balance

10


Class statement
class (,,...): Example: class vector3D: def __init__(self,x,y,z): self.x = x self.y = y self.z = z myVector = vector3D(4,7,2) # myVector is instance

Operator Overloading
· Operator meaning is said to Example of Overloading occurs when an operator's is changed. The new method of the class overload the operator. overloading + operator:

def __add__(self,other): return vector3D(self.x + other.x, self.y + other.y, self.z + other.z)

11


Special Class Methods
· __init__(self,args...) - Instance constructor · __del__(self) ­ Instance destructor · __repr__(self) ­ string representation for print, also __str__(self) works the same · __cmp__(self,other) ­ function for comparisons of instances of objects · There are many others p 34 ­39 Chapter 3 Types and Objects review.

Object Oriented Programming Concepts continued
· Inheritance ­ when an object is given access to the attributes of another class · Superclass ­ the class or classes another class inherits attributes from, (base class) · Subclass ­ A class that inherits attributes from another class Read Chapter 7 of Python Essential Reference

12


Inheritance
class A: varA = 42 def method1(self) print "This is method 1" class B(A): # class B inherits from A def method2(self) print "This is method 2" IofB = B() # create instance of B IofB.method2 # invokes B.method2 IofB.method1 # invokes A.method1

Name Resolution: The LGB Rule
· First local ­ function level
­ Names assigned inside a function def

· Second global ­ module
­ Names assigned at top-level of a module ­ Names declared "global" in function

· Third built-in - Python
­ Predefined names ­ open, len, print, etc.

13


LGB Scope Example
# global scope X = 99 def addY(Y): # local scope Z=X+Y return Z addY(2) # X and addY: global # Y and Z : locals # X is global # return and def built-in # addY in module: 101

LGB Scope Example 2
Y, Z = 1, 2 # global names in module def sum(): global X # declare globals assigned X=Y+Z# return None # None is a built-in meaning Null sum() # execute the function print X # I can print X outside the local function

14


System Command Controls
· commands module ­ 155 Python Ess. Ref. getoutput(command) getstatusoutput(command) p.

· os module: popen(command [, mode [,bufsize]]) p. 185 see call functions in spss.py,misc

commands module
import commands x = commands.getoutput('spss_time') print x # prints the output from the command spss_time Import string xList = string.split(x,'\n') # to create a list by line of output

15


commands.getstatusoutput
import commands status,commandoutput = commands.getstatusoutput(`cclist ­get testccl') print status print commandoutput

popen
>>> commandOutput = \ os.popen("cclist ­get testccl 2>&1","r") >>> out_string = commandOutput.read() >>> print out_string >>> stat = commandOutput.close() >>> print stat

16