2008年6月26日 星期四

module

a python file is a module

use import to import module:
ex:
import  test
this will import test.py

a module is imported only once per process by default. Further imports reuse loaded modules in memory
use sys.modules.keys() to find loaded module

when module is imported, the module is executed

module search path:
import modules in other directories:
set PHTYONPATH

import and from:
1. only use import:
ex:
import test
test.run()

2. use import and from
ex:
from test import run
run()
now we can reference run() without test
ex:
from test import *
now we can reference any attribute of module test

show module's attribute
ex:
test.__dict__.keys()

reload:
ex:
import test
reload(test)

module packages:
import  dir1.dir2.test
dir1 and dir2 are directories,  the file imported is test.py
dir1 and dir2 must both contain  __init__.py
dir1 must under the directory of python search path

2008年6月23日 星期一

loop

while  ... else...
the else is executed if break is not excuted in the while
ex:
while  x> 1:
          if  x>10
              break
else
        print  x

for ...  else  is the same as while ...  else ...

for applies to list, string , tuple

lambda

ex:
f= lambda x, y: x+y
f(1,2)
--->  3

2008年6月20日 星期五

define class

ex:
class Test:
     def  __init__(self, name):
     self.name=name

      def  hello(self):
             return  "hello"

t= Test("peter")
t.name
---> "peter"
t.hello
---> "hello"

set

a=set('abcd')
b=set('cdef')
a | b
---> set(['a', 'b', 'c', 'd', 'e',  'f'] )
a & b
--->   set( [ 'c', 'd' ] )
a - b
--->  set( [ 'a', 'b' ] )


file methods

open:
ex:
open('test.txt', 'w')

read:
return entire file into string

sorted, type

sorted
ex:
sorted([2,1])
--->  [1,2]

type:
know the object's type
ex:
type("test")
--->  <type , 'str'> 

check type methods:
(1) if type(a) ==type([]):
(2) if type(a)== list:
(3) if  isinstance(a, list):


for

ex:
for a in [1,2,3]:
    print  a

dictionary

use  {  }
ex:
test= { "a":"peter",  "b":"andy" }
---> test["a"]="peter"

keys:

has_key:

delete an element in dictionary:
ex:
a={ 'age':3  }
del  a['age']

regular expression

match
ex:
import re
match= re.match( '/(.*)/(.*)', 'abc/def/' )
match.groups()
---> ( 'abc', 'def' )

^:
match the start of  the string

$:
match the end of the string

{ }:
ex:
\d{1,2}
one or two numbers

string method

find:
return the offset of argument
ex:
'test'.find('es')
--->  1

replace:
a='test'
a.replace('t' , 'b')
--->  a is 'best'

split:
'aaa,bbb'.split(',')
--> [ 'aaa', 'bbb' ]

upper:
'test'.upper()
--->  'TEST'

isalpha(),  isdigit()

rstripe()
remove whitespace on the right side

ord
ex:
ord('a')
--> 97

""":
ex:
a= """
b
  ""
c
"""
print a
--->   b 
             ""
          c

format string:
ex:
n1=1
n2=2
print (" num1 %d num2 %d"  %(n1, n2) )



immutable object & mutable object

immutable object:
number,  string, tuple

mutable object:
list , dictionary 

slicing

apply to string, list
return a new string or list
ex:
a="test"
a[1:3]
--->  es
( offset 1 to 2, not including 3)

a[1:]
-->  est
( left offset defaults to the length of a)

a[:3]
--> tes
(right offset defaults to 0)

== & is

==:
compare value of  two object

is:
compare if two variables point to the same object
ex:
if a is b

in-place changes & non in-place changes

non in-place change:
for immutable object, such as number & string
ex:
a=3
b=a
b=2
--->  a=3 ,  b=2

in-place  changes:
for list , dictionary , etc
ex:
a=[1,2,3]
b=a
b[0]=5
--->  a=[5,2,3],  b=[5,2,3]


note:
a=[1,2]
b=a
b=[3,4]
--->  a is still [1,2]  because now  b & a point to different objects

the parameter of the function is passed by assignment 
Hence, it is the same.
If parameter is mutable, it can be changed
If parameter is not mutable, it can not be changed

how to change non-mutable argument for caller:
using return value
def  test(x, y)
     x=3
     y= 3
     return x, y
a=2
b=2
a, b= test(a, b)


list and tuple

list:
using []
ex:
a=[1,2,3]

+:
[1,2] +[3,4]
--> [1,2,3,4]

sort()

reverse()

get column from list:
ex:
a=[ [1,2], [3,4] ]
b=[ row[1] for row in a]
--> b= [2,4]
row[1] means second column
Hence, second column for each row

append:

tuple:
use ()
ex:
a= (1,2,3)
It is like list , but it is immutable 


dir & help

dir( module_name):
return all attributes inside that module

dir( "test")
--> string's attribute, such as string's methods

help:
find info about API
ex:
help("test".index)

define method

def  test( arg1 ):
        print "hello"

variable in the function

when assign a name A in a function, it will create a local variable a
In the function, we can read the value of global variable A
However, if you want to modify global variable A, you must using following methods:

global:
use global to modify global variable
ex:
x=1
def  test():
      global  x
      x=3

access attribute in other module:
using import
ex:
import  test
test.var = 2

nested function:
ex:
def test:
    x=3
    def  test2:
        print x
test2 can access x defined in test 

keyword parameter
ex:
def  test(a, b):
        print  a, b

test( a=3, b=2)

default parameter:
ex:
def  test(a, b=3):
       printf  a, b

test( 2)

arbitrary argument:
ex:
def  test(*args):
       print args

test( 1,2,3)

** is for keyboard argument
ex:
def  test(**args):
      print  args

test(a=1,b=2)

use * in caller:
unpack a collection of arguments
ex:
a= (1,2,3,4)
test( *a)

use ** in caller:
unpack a dictionary of key/value pairs