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):