python’perl’vs.’python’ • perl is worse than python because people wanted it worse. larry...

Post on 25-Jan-2020

3 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Python  

ESA  2011/2012  Adam  Belloum  

a.s.z.belloum@uva.nl      

Material  Prepared  by  Eelco  Schatborn    

ES:  Python  

•  Today:  1.  Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  FuncCons  3.  Regular  expression  4.  File  and  I/O  5.  Modules  6.  Packages  7.  Object  Oriented  Perl  8.  DocumentaCon  

IntroducCon  

•  WriUen  by  Guido  van  Rossum  •  Started  work  in  1990  •  First  release  in  1991  •  Minor  number  release  every  6  months  •  Named  aZer  Monty  Python  

       “Perl  is  executable  line  noise.  Python  is  executable  pseudo-­‐code.”  

What  is  Python  

•  a  general-­‐purpose  high-­‐level  programming  language  whose  design  philosophy  emphasizes  code  readability.    

•  Python  aims  to  combine  "remarkable  power  with  very  clear  syntax”,  and  its  standard  library  is  large  and  comprehensive.    

•  Its  use  of  indentaCon  for  block  delimiters  is  unusual  among  popular  programming  languages.  

hUp://en.wikipedia.org/wiki/Python_%28programming_language%29  

Perl  vs.  Python  

•  Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998

•  I would actively encourage my competition

to use Perl. Sean True, 30 Mar 1999

•  if you look at from 10 KM above, perl, python, and ruby are the same …  guido van rossum , pycon-2012  

Why  I  Love  Python                        ©2001    www.BruceEckel.com  

Last  news  about  Python    from  Guido  van  Rossum  

•  Keynote:  Guido  Van  Rossum  given  at    pycon-­‐2012  (Same  talk  was  given  at  the  UvA  last  July)  –  Trolls:  a  quesCon  that  isn’t  meant  as  a  quesCon,  but  to  heckle  •  “Python  Sucks.  Ruby  Rules”  •  “When  will  you  admit  Python  3  is  a  mistake?”  •  “Since  PyPy  is  so  much  faster  than  CPython,  why  not  abandon  CPython”  

•  Etc.  

Notes:  hUps://andrew-­‐schoen-­‐pycon-­‐2012-­‐notes.readthedocs.org/en/latest/sunday/keynote.html    

Video:  hUp://ontwik.com/python/pycon-­‐2012-­‐keynote-­‐guido-­‐van-­‐rossum/    

10  Reasons  to  Learn  the  Python  Programming  Language  

1.  Reduced  CluUer  2.  It’s  not  backward-­‐compa5ble  in  exchange  for  pain  3.  It  doesn’t  value  performance  over  your  producCvity  4.  It  doesn’t  treat  you  like  stupid  5.  I  don’t  wait  forever  for  a  full  implementaCon  of  the  

language  6.  It  doesn’t  make  assumpCons  about  how  we  discover  

errors  7.  MarkeCng  people  are  not  involved  8.  You  don’t  have  to  type  so  much  9.  your  guesses  are    usually  right  10. Python  lets  you  focus  on  concepts  

Why  I  Love  Python                        ©2001    www.BruceEckel.com  

DocumentaCon  :  Pydoc  

•  Commandline     $ pydoc sys!!

•  Web  browser:    –  pydoc  start  an  HTTP  server  on  the  local  machine  that  will  serve  documentaCon  to  visiCng  Web  browsers.    $ pydoc -p 1234 # start a HTTP server on port 1234!$ pydoc -g # start the server and ! # additionally bring up a small!!

   

Simple  Python  

A  simple  program  to  start  with:        #!/usr/bin/python principal = 1000 # initial amount rate = 0.05 # interest rate numyears = 5 # number of years year = 1 while year <= numyears: principal = principal*(1+rate) print year, principal year += 1  

The  Python  Interpreter  •  Normal  method  for  scripCng  using    

#!/usr/bin/python

•  python  is  also  an  interacCve  interpreter  you  can  interpret  single  lines  of  code  good  for  simple  checking  and  debugging  

$ python mypythonprogram.py!

$ python![GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin!

Type "help", "copyright", "credits" or "license" for more information.!

>>> !

ES:  Python  

•  Today:  1.  Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  FuncCons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Perl  8.  DocumentaCon  

Variables  

•  Python  is  a  dynamically  typed  language:  names  can  represent  values  of  different  types  during  the  execuCon  of  the  program.  

•  Names  or  idenCfiers    – must  begin  with  a  non-­‐numeric  character  or  underscore    –  but  may  contain  both  numeric  and  non-­‐numeric  characters  

Troll  about  dynamic  type  “I  don’t  want  my  app  to  fail  witn  an  A9ributeError  a;er  running  for  4  hours”  

Dynamic  types  (Weak  typing)  

•  “You  write  what  you  want  to  do,  let  Python  worry  about  how”  

•  weakly  typed  programming  languages  are  those  that  support  implicit  type  conversion  

•  Argument  for    –   dynamic  typing  is  that  it  requires  less  effort  on  the  part  of  the  programmer,  because  the  interpreter  implicitly  performs  certain  conversions  

•  Argument  against  –   dynamic  typing:  “errors  won’t  be  found”  

Variables:  Numbers  (1)  simple  numbers  the  same  as  with  perl:  •  decimal:  12, -17, 255, … •  octal,  start  with  0: 015, -023, 0777, … •  hexadecimal,  start  with  0x: 0xc, -0x11, 0xff,…

floaCng  point  numbers:  •  ”one  and  a  quarter":  1.25  But  also  imaginary  numbers:  •  wriUen  as  'numberj',    for  example:  1.23j

Variables:  Numbers  (2)  

•  Complex  numbers,  using  imaginary  numbers:  –  wriUen  as:    num1 + num2j,    –  or  can  be  created  with:    complex(real, imag)  funcCon.  

         (1.0j * 1J) è (-1+0j)

Variables:  Strings  (1)  

•  To  create  string  literals,  enclose  them  in  single,  double  or  triple  quotes.  

Examples:  'Hello World' "Python is groovy"

"""Sino si Pepito Biglangliko?"""

•  The  same  type  of  quote  used  to  start  the  string  must  be  used  to  terminate  it.  

Variables:  String  (2)  

•  Escape  sequences  represent  special  characters:  \n, \t, . . .

•  Both  in  double  quoted  (")  and  single  quoted  (')  strings  

•  For  verba5m  strings  use  raw  strings  using  r'.  .  .  '  >>> print "Hi there! \n \t It's me.\n" Hi there!

It's me.

>>> print r'And me \n \t as well!' And me \n \t as well!

Variables:  Strings  (3)  •  Triple-­‐quoted  strings  using  either  """or  ‘’’  capture  all  the  

text  that  appears  before  the  terminaCng  triple  quote.  

–  Single  and  double  quoted  strings  must  be  on  one  logical  line.  –  Triple-­‐quoted  strings  are  useful  when  contents  of  the  string  span  

mul5ple  lines  of  text.    

–  For  example:  >>> print """ … Usage: thingy [OPTIONS] … -h Display this usage message … -H hostname Hostname to connect to …"""

•  String  literals  can  span  mul5ple  lines  using  a  closing  backslash  ('\')  

•  The  backslash  is  for  syntax  purposes  only,  it  is  not  included  in  the  output  

>>> print "Hi \ … there! \n\ … \t It's me.\n”  

prints:  Hi there! It's me.

Variables:  Strings  (4)  

Variables:  Strings  (5)  •  Strings  are  indexed  like  lists,  starCng  at  0  •  You  can  use  them  using  the  index  operator  '[i]'  

>>> a = "Hello World" >>> b = a[4] >>> b o

•  Substrings  can  be  used  by  slicing:  `[i:j]’  >>> a[0:6] "Hello " >>> d = a[7:] "World" >>> e = a[3:8] "lo Wo"

Variables:  Strings  (6)  

 Other  data  types  can  be  converted  into  a  string  using  either  str()  or  repr()  funcCons  or  backquotes  (`),  which  are  a  shortcut  notaCon  for  repr().  

Examples

>>> x = 5.2 >>> s = "The value of x is " + str(x) >>> s The value of x is 5.2

>>> s = "The value of y is " + repr(y) >>> s = "The value of y is " + `y`

Operators:  numbers    

•  The  following  operators  for  numbers  apply:            +, -, *, /, //, % …

•  C-­‐style  shiZing  &  masking   1<<16, x&0xff, x|1, ~x, x^y •  Integer  division  truncates    

•  1/2  -­‐>  0  #  1./2.  -­‐>  0.5,  float(1)/2  -­‐>  0.5  \\          >>> width = 20 >>> height = 5*9

>>> width * height 900

Operators:  Strings  

•  Strings  can  be  concatenated  using  a  '+'  •  But  also  by  wriCng  them  adjacent  to  each  other:  

Examples    >>> print "Hello" + 'Python' HelloPython >>> print "Python " "says" ' Hello!'

Python says Hello!

Reference  SemanCcs  

•  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]  

a  

1   2   3  

b  

a  

1   2   3  

b  

4  

a  =  [1,  2,  3]  

a.append(4)  

b  =  a  

a   1   2   3  

Slide  25        ©2001,  2002  Guido  van  Rossum  

a  

1  

b  

a  

1  b  

a  =  1  

a  =  a+1  

b  =  a  

a   1  

2  

Changing  an  Integer  

old  reference  deleted  by  assignment  (a=...)  

new  int  object  created  by  add  operator  (1+1)  

Slide  26        ©2001,  2002  Guido  van  Rossum  

Play  around  1  

•  Write  a  short  python  prog,  which  when  you  enter  our  name  it  prints  :  Hi  !  <your  name>  .  

•  Hint:  use  raw_input()  to  get  the  input  

>>> name = raw_input('What is your name?\n')

>>> What is your name? OS3

>>> print 'Hi, ' + name + '.' Hi, OS3.

Variables:  Lists  (1)  •  lists  and  tuples  are  sequences  of  arbitrary  objects  You  

can  create  a  list  as  follows:  >>> names = [ "Eric", "Trixie", "Coley" ]

     They  too  are  indexed:  >>> a = names[2] a is now "Coley" >>> names[0] = ”Jan" >>> names[0] Jan

•  append  a  new  member  to  the  end  of  a  list  using  append()  >>> names.append("Khamir") >>> names [ "Eric", "Trixie", "Coley", "Khamir" ]

Variables:  Lists  (2)  •  You  can  extract  or  reassign  a  por5on  of  a  list  by  using  the  slicing  

operator.    Examples    

>>> names = ["pusakat","Trixie","Coley","Khamir"] >>>names[0:2]

["pusakat", "Trixie”] >>> names[2:]

["Coley", "Khamir" ]

     •  Use  the  plus  ('+')  operator  to  concatenate  lists.    

>>> a = [1,2,3] + [4,5] >>> a [1,2,3,4,5]

Variables:  Lists  (3)  •  Lists  can  contain  any  kind  of  Python  object  including  

other  lists.  

Example:  >>> a = [1,"Dave”,3,["Mark”,9,[100, 101]],10]

 

•  Nested  lists  are  accessed  as  follows:  >>> a[1] "Dave" >>> a[3] ['Mark', 9, [100, 101]] >>> a[3][2][1] 101

 

Variables:  Tuples  

•  Tuples  are  a  lot  like  lists  –  Tuples  support  most  of  the  same  funcCons  as  a  list  –  They  are  however  immutable  aZer  creaCon  –  Used  to  return  mul5ple  values  from  a  funcCon  

•  You  can  create  tuples  by  enclosing  a  group  of  values  in  parentheses  ('(.  .  .  )')  or  with  a  comma-­‐separated  list.  

>>> a = (1,4,5,-9,10,'hello!’) >>> b = (7,) # this is a singleton >>> c = a, b >>> c ((1,4,5,-9,10,'hello!’),(7,))

Variables:  DicConaries  (1)  •  A  dic5onary  is  an  associa5ve  array  or  hash  table  that  

contains  objects  indexed  by  keys.  •  Only  immutable  objects  can  be  used  as  a  key,  like  

strings,  numbers,  tuples,  etcetera.  •  You  create  a  dicConary  by  enclosing  values  in  curly  

braces  ('{.  .  .  }'):  >>>>    a = { … "username" : "xenos", … "home" : "/home/xenos", … "uid" :500 … } >>> a ["uid"] 500

Variables:  DicConaries  (2)  •  Access  any  value  using  it's  key:  

 >>>  a["username"] "xenos" >>> a["home"] "/home/xenos”

•  To  insert  or  modify  objects,  you  assign  a  value  to  a  key-­‐indexed  name.  

 a["username"] = "trixie" a["home"] = "/home/trixie" a["shell"] = "/usr/bin/tcsh”

Variables:  DicConaries  (3)  

DicConary  membership  is  tested  with  the  has_key()  method:  if a.has_key("username"): username = a["username"]

else: username = "unknown user"

This  can  also  be  performed  more  compactly  this  way.  username = a.get("username", "unknown user")

 Variables:  DicConaries  (4)  

•  To  obtain  a  list  of  dicConary  keys,  use  the  keys()  method.  

 k = a.keys() k = ["username", "home", "uid", "shell" ]

•  Use  the  del  statement  to  remove  an  element  of  a  dicConary.  

 del a["username"]

ES:  Python  

•  Today:  1.   Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  funcCons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Perl  8.  DocumentaCon  

Flow  control  

•  A  block  of  code  contains  a  list  of  statements.  •  Code  blocks  are  denoted  by  using  indenta5on  •  Flow  control  can  be  exerted  using  looping  or  condiConal  Statements.  

Looping  Statements  (1)  

•  Iterates  over  the  members  of  a  sequence,  such  as  a  string,  list  or  tuple.  

>>>for i in ( 1, 2, 3, 4, 5, 6, 7, 8, 9 ): … print "2 to the power %d is %d” % (i, 2**i)

•  Using  the  range()  funcCon  you  can  also  give  a  range:  >>> for i in range(1,10):

… print "2 to the power %d is %d” % (i, 2**i)

Looping  Statements  (2)  

•  The  for  statement  can  iterate  over  any  sequence  type  and  isn't  limited  to  sequences  of  integers.  >>>  a = "Hello World” # Print out the characters in a >>> for c in a:

… print c

>>> b = ["Eric", "Trixie", "Coley", "Khamir”]

# Print out the members of a list

>>> for name in b: … print name

Looping  Statements  (3)  

# a = [0,1,2,3,4] # b = [1,2,3,4,5,6,7]

# c = [0,3,6,9,12] # d = [8,7,6,5,4,3,2]

•  The  range(i,  j)  funcCon  constructs  a  list  of  integers  with  values  from  i  to  j  à  1.  

•  If  the  starCng  value  is  omiUed,  it's  assumed  to  be  zero.  

•  An  opConal  stride  or  step  size  can  be  given  as  a  third  •  argument.  

a = range(5)

b = range(1,8) c = range(0,14,3)

d = range(8,1,-1)-1)

Play  around  2  

•  Write  a  short  python  prog,  which  iterate  through  a  list  and  print  the  iteraCon  

•  Hint:  use  enumerate()  to  iterate  through  the  list  

my_list = ['john', 'pat', 'gary', 'michael']

for i, name in enumerate(my_list):

print "iteration %i is %s" % (i, name))

Play  Around  3  

•  Write  a  short  prog  in  python,  which  prints    amount  of  money  you  have  to  pay  for  a  given  purchase    let  say:  1  kg  (apples  à1.40  euro/kg),  3  kg  (banana    à1.20  euro/kg)  

•  Hint:  use  dicConary,     prices = {'apple': 1.40, 'banana': 1.20} my_purchase = { 'apple': 1, 'banana': 6} grocery_bill = sum( prices[fruit] * my_purchase[fruit] \ for fruit in my_purchase) Print 'I owe the grocer $%.2f' % grocery_bill :

CondiConal  Statements  (1)  

The  if  statement:    if test: ... elif test: ... else:

...

•  The  usual  comparison  operators  for  tesCng:  <, >, ==, !=, <=, >=

•  They  work  on  most  Python  objects

The  while  statement:  while test:

...

CondiConal  Statements  (2)  •  if  statement  example:  

if a == 5: print "It's five!" elif a == 6: print "It's six!" else: print "It's something else.”  

•  while  statement  example:  a = 0 while a < 3: a = a +1 print "Counting up to 3..."

Play  Around  4  •  Write  a  short  prog  in  python  which  uses  the  local  Cme  to  print  

something  (  your  acCviCes  during  the  day).  

•  Hint:  import  Cme,  Cme.localCme(),    to  get  the  hours  myCme.tm_hour()  

import time now = time.localtime() hour = now.tm_hour if hour < 8: print 'sleeping' elif hour < 9: print 'commuting' elif hour < 17: print 'working' elif hour < 18: print 'commuting' elif hour < 20: print 'eating' elif hour < 22: print 'resting' else: print 'sleeping'

ES:  Python  

•  Today:  1.  Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  FuncCons  3.  Regular  expression  4.  File  and  I/O  5.  Packages  6.  Object  Oriented  Perl  7.  DocumentaCon  

FuncCons  (1)  

•  funcCons  can  be  defined  using  def  def fibo(n): # calculate fibonacci up to n ...  

•  arguments  can  have  default  values  through  assignment  in  the  definiCon  def fibo(n=100): # n has default value 100

...  

FuncCons  (2)  

def  name(arg1,  arg2,  ...):          """documentaBon"""  #  opConal  doc  string          statements    return  expression                #  from  funcCon  

FuncCon  (3)  

•  Return  values  without  a  return  value  a  funcCon  returns  None        

•  Example  def fibo(n): # return Fibonacci series up to n result = []

a, b = 0, 1

while b < n: result.append(b) # see below

a, b = b, a+b

return resultturn result

FuncCon  (4)  

•  Usage  –  calling  the  example  funcCon  without  an  argument      >>> fibo() # call it [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

 –  calling  the  example  funcCon  with  an  argument     >>> fibo(50) # call it again [1, 1, 2, 3, 5, 8, 13, 21, 34]

Play  Around  5  

•  Write  a  short  prog  in  python  which  has  a  funcCon  with  greets  the  name  given  as  arguments  

def greet(name): print 'hello', name

greet('Jack')

>>> hello, Jack

ES:  Python  

•  Today:  1.   Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  funcCons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Perl  8.  DocumentaCon  

Regular  Expressions  

•  Import  the  re  package  to  use  regular  expressions  •  A  number  of  funcCons  are  available  in  re  package:  

match()

search()

split() sub()

. . .

•  For  more  informaCon  see  the  documentaCon  $  pydoc  re  

 

Regular  Expressions  •  If  we    want  to  write  a  prog  in  python,  which  match  a  regexp  to  

validate  a  list  of  phone  number  in  USA   import re for test_string in ['555-1212', 'ILLEGAL’]:

if re.match(r'^\d{3}-\d{4}$', test_string): print test_string,'is a valid phone number'

else: print test_string, 'rejected'    

Regular  Expressions  •  If  we    want  to  write  a  prog  in  python,  which  match  a  regexp  to  validate  

a  list  of  phone  number  in  USA   >>> import re >>>  m  =  re.match(r"(\w+)  (\w+)",  "Isaac  Newton,  physicist")  >>>  m.group(0)              #  The  enCre  match  'Isaac  Newton'  >>>  m.group(1)              #  The  first  parenthesized  subgroup.  'Isaac'  >>>  m.group(2)              #  The  second  parenthesized  subgroup.  'Newton'  >>>  m.group(1,  2)        #  MulCple  arguments  give  us  a  tuple.  ('Isaac’,    ‘Newton’)  

Play  Around  5    •  Write  a  short  prog  in  python,  which  open  all  files  in  you  current  directory  

and  prints  its  content  

•  Hint:  use  glob  module,    –  open  (filename)  to  open  a  file      –  glob.glob('*.py’)  Unix  style  pathname  extensions  –     

import glob # glob supports Unix style pathname extensions python_files = glob.glob('*.py') for fn in sorted(python_files):

print ' ------', fn for line in open(fn): print ' ' + line.rstrip()

print

Play  Around  6  •  Write  a  short  prog  in  python  which  sum  up  integers  in  

the  command  line    •  Hint:  important  sys  module,  try:  …  except  ValueError:    

import sys

try: total = sum(int(arg) for arg in sys.argv[1:]) print 'sum =', total

except ValueError: print 'Please supply integer arguments'

ES:  Python  

•  Today:  1.   Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  funcCons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Perl  8.  DocumentaCon  

Reading Files

name = open("filename") –  opens the given file for reading, and returns a file object

name.read() - file's entire contents as a string

>>> f = open("hours.txt") >>> f.read() '123 Susan 12.5 8.1 7.6 3.2\n 456 Brad 4.0 11.6 6.5 2.7 12\n 789 Jenn 8.0 8.0 8.0 8.0 7.5\n'

hUp://www.cs.washington.edu/educaCon/courses/cse143/12wi/python.shtml  

Line-based File Processing

name.readline() - next line from file as a string

–  Returns an empty string if there are no more lines in the file

name.readlines() - file's contents as a list of lines

>>> f = open("hours.txt") >>> f.readline() '123 Susan 12.5 8.1 7.6 3.2\n'

>>> f = open("hours.txt") >>> f.readlines() ['123 Susan 12.5 8.1 7.6 3.2\n', '456 Brad 4.0 11.6 6.5 2.7 12\n', '789 Jenn 8.0 8.0 8.0 8.0 7.5\n']

Writing Files name = open("filename", "w") # write name = open("filename", "a") # append

–  opens file for write (deletes any previous contents) , or –  opens file for append (new data is placed after previous data)

name.write(str) - writes the given string to the file name.close() - closes file once writing is done

>>> out = open("output.txt", "w") >>> out.write("Hello, world!\n") >>> out.write("How are you?") >>> out.close()

>>> open("output.txt").read() 'Hello, world!\nHow are you?'

hUp://www.cs.washington.edu/educaCon/courses/cse143/12wi/python.shtml  

Line-based Input Template

•  A file object can be the target of a for ... in loop

•  A template for reading files in Python:

for line in open("filename"): statements

>>> for line in open("hours.txt"): ... print(line.strip()) # strip() removes \n 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jenn 8.0 8.0 8.0 8.0 7.5

hUp://www.cs.washington.edu/educaCon/courses/cse143/12wi/python.shtml  

ES:  Python  

•  Today:  1.   Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  funcCons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Perl  8.  DocumentaCon  

Modules  (1)  

•  A  module  is  a  file  containing  Python  defini5ons  and  statements.  

•  The  file  name  is  the  module  name  with  the  sux  .py  appended.  

•  Within  a  module,  the  module's  name  (as  a  string)  is  available  as  the  value  of  the  global  variable    

__name__.  

Modules  (2)  

•  Example  module  fibo.py  

# Fibonacci numbers module

def fibo(n): # write Fibonacci # series up to n a, b = 0, 1

while b < n: print b a, b = b, a + b

Modules  (3)  •  Import  the  module  with  the  following  command:  

 >>> import fibo •  The  funcCons  are  not  included  directly  •  Using  the  module  name  you  can  access  the  funcCons:  

    >>> import fibo >>> fibo.fibo(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.__name__ 'fibo'

Modules  (4)  

•  If  you  intend  to  use  a  funcCon  oZen  you  can  assign  it  to  a  local  name:  

 >>> fib = fibo.fibo >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Modules  (5)  •  The  built-­‐in  funcCon  dir()  can  be  used  to  find  out  which  

names  a  module  defines.  It  returns  a  sorted  list  of  strings:   >>> import fibo >>> dir(fibo) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', , 'fibo']

•  It  lists  all  types  of  names:  variables,  modules,  func5ons,  etc.  

•  Without  arguments,  dir()  lists  the  names  you  have  defined  currently  

ES:  Python  

•  Today:  1.   Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  funcCons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Perl  8.  DocumentaCon  

Packages  (1)  

•  Packages  are  a  way  of  structuring  Python's  module  •  namespace  by  using  doMed  module  names".  •  They  hide  module  names  from  other  packages  •  They  are  made  up  of  modules  in  a  parCcular  hierarchic  file  system  

•  Each  directory  name  is  apart  of  the  module  structure  

Packages  (2)  •  An  example  Package:  

Sound/ Top-level package __init__.py Initialization Formats/ file format conversions/ __init__.py wavread.py ... ...

•  __init__.py  files  are  required  to  make  Python  treat  the  directories  as  containing  package  

•  __init__.py can  just  be  an  empty  file,  but  it  can  also  execute  iniCalizaCon  code  for  the  package.  

Packages  (3)  •  Import  individual  modules  from  the  package:  

import Sound.Effects.echo –  Any  func5ons  in  a  package  must  sCll  be  referenced  by  their  fully  qualified  name   Sound.Effects.echo.echofilter( ... )

•  An  alternaCve  way  of  imporCng  the  submodule  is:  from Sound.Effects import echo –  This  also  loads  the  submodule  echo,  and  makes  it  available  without  its  package  prex  

(Sound.Effects).  

echo.echofilter( ... )

•  Import  all  modules  from  the  package:  from Sound.Effects import *

ES:  Python  

•  Today:  1.   Python  introducCon  2.  Basic  Python:  types,  variables,  statements,  funcCons  3.  Regular  expression  4.  File  and  I/O  5.  Modules    6.  Packages  7.  Object  Oriented  Perl  8.  DocumentaCon  

Class  •  Declare  a  class  by    class  <classname>:  

–  class  defini5ons  introduce  new  a  namespace,  with  its  OWN  scope  –  all  definiCons  within  a  class  definiCon  are  in  that  new  scope  

•  Use  a  class  from  <classname>  import  *  

–  client  programs  must  import  the  classes  they  use  –  the  file  name  (lowercase),  not  class  name,  is  used  

•  classes  can  be  instan5ated  into  instance  objects  

           from myclass import *!

 x = MyClass() # It creates a new instance of the class and assigns this !! ! ! ! ! # object to the local variable x,!! ! ! ! ! # which now represents an instance object.!! ! ! ! ! !!! ! ! ! ! ! ! ! ! ! !  

Class  Method  (Method  Objects)  

•  The  first  argument  of  any  funcCon  within  a  class  is  an  object  reference  to  a  class  instance  

   class MyClass: i = 12345 def f(self): return 'hello world’

•  A  class  constructor  is  a  special  method  named    def __init__(self [, param1, ..., param_n]): …

Class  Method  (Method  Objects)  

•  Class  Methods  –  The  first  argument  is  always  the  object  itself       def <methodname>(self, parm1, param2): self.param1 = … self.param2 = … …  

•  Method  objects  are  instan5a5ons  of  func5ons  in  a  class.  

–  the  call  method  object    through  the  instance  object  x.f()

Class  instance  (instance  object)  •  You  can  create/delete  aMributes  from  an  instance  object  (not  

from  a  class  object)  –  create  by  assignment  –  delete  by  using  del.  

 x.counter = 1 # creates a new attribute of!! ! ! ! ! ! ! ! # the instance object x

while x.counter < 10:

x.counter *= 2 print x.counter

del x.counter # delete attribute from the !!! !! !! !! # instance object x

Example  of  class  class BankAccount(object):

def __init__(self, initial_balance=0): self.balance = initial_balance

def deposit(self, amount): self.balance += amount

def withdraw(self, amount): self.balance -= amount

def overdrawn(self): return self.balance < 0

my_account = BankAccount(15) my_account.withdraw(5) print my_account.balance

hUp://wiki.python.org/moin/SimplePrograms  

Printing Objects

•  By default, Python doesn't know how to print an object:

•  We'd like to be able to print a Point object and have its state shown as the output.

>>> p = Point(5, -2) >>> print p <Point instance at 0x00A8A850>

hUp://www.cs.washington.edu/educaCon/courses/cse143/12wi/python.shtml  

Printable Objects: __str__

def __str__(self): return string

–  converts an object into a string (like Java toString) –  invoked automatically when str or print is called def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"

>>> p = Point(5, -2) >>> print p (5, -2) >>> print "The point is " + str(p) + "!" The point is (5, -2)!

hUp://www.cs.washington.edu/educaCon/courses/cse143/12wi/python.shtml  

DocumentaCon  

 •  Use  the  web,  there  are  a  lot  of  websites  on  python  •  Check  www.python.org  for  help.  •  Use  the  pydoc  tool,  python  manual  pages  etcetera.  

Material  for  these  slides  was  taken  from  hUp://www.python.org/doc  hUp://www.cs.washington.edu/educaCon/courses/cse143/12wi/python.shtml  

 

Assignment    •  Create  a  class  python  for  keeping  track  of  the  various  hardware  

configuraCon  and  their  relaCon  to  each  other  as  used  in  our  Lab.  Note  that  there  are  different  types  of  hardware  and  relaCons.  

•  So,  define  a  number  of  types  of  hardware  and  a  number  of  types  if  relaCons  (direct  cable  network,  etc)  and  create  a  single  class  that  can  be  instanCated  to  represent  each  and  every  one  of  them.  The  instance  objects  must  be  connected  through    relaCons  to  represent  ,  in  the  end  ,  the  OS3  Lab  in  an  abstract  sense.  So  the  objects  represent  a  tree  structure  represenCng  the  lab  as    whole  .  

•  So  as  an  example:  your  desktop  machine  has  a  keyboard  a  mouse  and  two  screens  directly  aUached  to  it.  The  desktop  computer  itself  is  connected  to  the  experimentaCon  machines  through  a  network.  Then  describe  the  experiment  machines  etc,  etc.  

Assignment    •  The  following  funcCons  must  be  made  available  for  each  node  or  piece  of  

hardware  

•   Print  –  should  print  the  info  of    the  certain  piece  only  –  this  includes  the  hardware  descripCon  at  least.  You  could  only  also  include  it’s  

posiCon  Cn  the  lab/server  room,  its  color  etc.  •  Printall  

–  Should  print  he  informaCon  for  this    piece    and  all  its  descendant    –   this  should    traverse  the  object  downwards  only  

 Bonus              Thinks  of    way  to  create  and  a  actual  descripCon  of  the  lab  on  top  of  the  

abstract  descripCon,  so;  add  the    name  of  a  computer  and  who  sits  behind  it  etc.  this  implies  that  there  can  be  many  desktops  computer  instances  that  look  exactly  the  same  hardware  wise,  but  have  different  owners.    

top related