顯示具有 python general 標籤的文章。 顯示所有文章
顯示具有 python general 標籤的文章。 顯示所有文章

2008年7月29日 星期二

python imaging library

If model in Django wants to use ImageField,  we must install python imaging library

2008年7月18日 星期五

exception

ex:
ckass Bad(Exception):
          pass

def test():
      raise  Bad(), "test bad"

try:
    test()
except  Bad, info:
     print "bad", info
else:
    print "else"
finally:
     print "finally"

assert:
raise AssertionError when test evaluates to false
ex:
assert  x<=3, 'x must be larger than 3'

raise:
ex1: raise object
class A:
     pass
def  test():
     raise A()

ex2:  raise string
message="Error"
def test():
      raise  message

2008年7月14日 星期一

change type

int:
string to int

str:
int to string

2008年7月13日 星期日

class method & static method

class method:
ex:
def  test(cls):
       print('class method')
test=classmethod(test)

static method:
ex:
def  test()
      print('static method')
test=staticmethod(test)



raw string

using r:
turn off escpate
ex:
tempStr=  r'C:\test'

python path

print python path:
import sys
print  sys.path

__name__ & __main__

when the file is run as a top-level program,  __name__ is set as __main__

when the file is imported,  __name__ is set to the module's name

Hence, we can use __name__ to do unit test.
If  __name__ == __main__,   we execute unit test
if __name__ != __main__,  unit test is not executed 


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)