一、eclipse的使用
- 可能是全宇宙最好用的IDE
- debug
- 查看執行過程
- 查看源碼
二、模塊的常用方法
- __name__
- __file__
- __doc__
三、函數
- 參數
- 參數默認值
- 可變參數
- 返回值

''' def Foo(): print 'Foo' def Foo(arg) print arg def Foo(arg='alex'): print arg #必須放在最后 def Foo(arg1,arg2): print arg1,arg2 Foo(arg2='alex',arg1='kelly') def Foo(arg,*args): print arg,args Foo('alex','kelly','tom') def Foo(**kargs): print kargs.keys() print kargs.values() Foo(k1='sb',k2='alex') '''
四、yield

def AlexReadlines(): seek = 0 while True: with open('D:/temp.txt','r') as f: f.seek(seek) data = f.readline() if data: seek = f.tell() yield data else: return for i in AlexReadlines(): print i
五、三元運算和lambda表達式
result = 'gt' if 1>3 else 'lt' print result
a = lambda x,y:x+y print a(4,10)
六、內置函數
#print help() print dir() print vars() #print type() import temp import temp reload(temp) id([12]) #is ------------------ cmp(2,3) cmp(2,2) cmp(2,1) cmp(10,1) abs() bool() divmod() max() min() sum() pow(2, 11) ------------------ len() all() any() ------------------ chr() ord() hex() oct() bin() ------------------ print range(10) print xrange(10) for i in xrange(10): print i for k,v in enumerate([1,2,3,4]): print k,v ------------------ s= 'i am {0}' print s.format('alex') str(1) ------------------ def Function(arg): print arg print apply(Function,('aaaa')) #執行函數 print map(lambda x:x+1,[1,2,3]) #all print filter(lambda x: x==1,[1,23,4]) #True序列 print reduce(lambda x,y:x+y,[1,2,3]) #累加 x = [1, 2, 3] y = [4, 5, 6] z = [4, 5, 6] print zip(x, y,z) ------------------ #__import__() #hasattr() #delattr() #getattr() module = __import__('temp') print dir(module) val = hasattr(module, 'version') print val ------------------ #callable() #函數、類必須要有 __call__ 方法 #compile #eval com = compile('1+1','','eval') print eval(com) #exec語句 code = "for i in range(0, 10): print i" cmpcode = compile(code, '', 'exec') exec cmpcode code = "print 1" cmpcode = compile(code, '', 'single') exec cmpcode ------------------ #isinstance() #issubclass() #super() #staticmethod()
更多,猛擊這里
七、常用模塊
1、random 用於生成隨機數
import random print random.random() print random.randint(1,2) print random.randrange(1,10)
應用場景:生成隨機驗證碼
import random checkcode = '' for i in range(4): current = random.randrange(0,4) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += str(temp) print checkcode
2、md5 加密
import md5 hash = md5.new() hash.update('admin') print hash.hexdigest() import hashlib hash = hashlib.md5() hash.update('admin') print hash.hexdigest()
3、序列化和json
4、re
- compile
- match search findall
- group groups
正則表達式常用格式:
字符:\d \w \t .
次數:* + ? {m} {m,n}
5、time
import time #1、時間戳 1970年1月1日之后的秒 #3、元組 包含了:年、日、星期等... time.struct_time #4、格式化的字符串 2014-11-11 11:11 print time.time() print time.mktime(time.localtime()) print time.gmtime() #可加時間戳參數 print time.localtime() #可加時間戳參數 print time.strptime('2014-11-11', '%Y-%m-%d') print time.strftime('%Y-%m-%d') #默認當前時間 print time.strftime('%Y-%m-%d',time.localtime()) #默認當前時間 print time.asctime() print time.asctime(time.localtime()) print time.ctime(time.time()) import datetime ''' datetime.date:表示日期的類。常用的屬性有year, month, day datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond datetime.datetime:表示日期時間 datetime.timedelta:表示時間間隔,即兩個時間點之間的長度 timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) strftime("%Y-%m-%d") ''' import datetime print datetime.datetime.now() print datetime.datetime.now() - datetime.timedelta(days=5)
6、sys
sys.argv 命令行參數List,第一個元素是程序本身路徑 sys.exit(n) 退出程序,正常退出時exit(0) sys.version 獲取Python解釋程序的版本信息 sys.maxint 最大的Int值 sys.maxunicode 最大的Unicode值 sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 sys.platform 返回操作系統平台名稱 sys.stdout.write('please:') val = sys.stdin.readline()[:-1] print val
7、os
os.getcwd() 獲取當前工作目錄,即當前python腳本工作的目錄路徑 os.chdir("dirname") 改變當前腳本工作目錄;相當於shell下cd os.curdir 返回當前目錄: ('.') os.pardir 獲取當前目錄的父目錄字符串名:('..') os.makedirs('dirname1/dirname2') 可生成多層遞歸目錄 os.removedirs('dirname1') 若目錄為空,則刪除,並遞歸到上一級目錄,如若也為空,則刪除,依此類推 os.mkdir('dirname') 生成單級目錄;相當於shell中mkdir dirname os.rmdir('dirname') 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname os.listdir('dirname') 列出指定目錄下的所有文件和子目錄,包括隱藏文件,並以列表方式打印 os.remove() 刪除一個文件 os.rename("oldname","newname") 重命名文件/目錄 os.stat('path/filename') 獲取文件/目錄信息 os.sep 輸出操作系統特定的路徑分隔符,win下為"\\",Linux下為"/" os.linesep 輸出當前平台使用的行終止符,win下為"\t\n",Linux下為"\n" os.pathsep 輸出用於分割文件路徑的字符串 os.name 輸出字符串指示當前使用平台。win->'nt'; Linux->'posix' os.system("bash command") 運行shell命令,直接顯示 os.environ 獲取系統環境變量 os.path.abspath(path) 返回path規范化的絕對路徑 os.path.split(path) 將path分割成目錄和文件名二元組返回 os.path.dirname(path) 返回path的目錄。其實就是os.path.split(path)的第一個元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\結尾,那么就會返回空值。即os.path.split(path)的第二個元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是絕對路徑,返回True os.path.isfile(path) 如果path是一個存在的文件,返回True。否則返回False os.path.isdir(path) 如果path是一個存在的目錄,則返回True。否則返回False os.path.join(path1[, path2[, ...]]) 將多個路徑組合后返回,第一個絕對路徑之前的參數將被忽略 os.path.getatime(path) 返回path所指向的文件或者目錄的最后存取時間 os.path.getmtime(path) 返回path所指向的文件或者目錄的最后修改時間
8、裝飾器
''' def foo(): print 'foo' def foo(): print 'before do something' print 'foo' print 'after' def foo(): print 'foo' def wrapper(func): print 'before' func() print 'after' wrapper(foo) def foo(): print 'foo' def wrapper(func): def result(): print 'before' func() print 'after' return result Do = wrapper(foo) Do() ''' def wrapper(func): def result(): print 'before' func() print 'after' return result @wrapper def foo(): print 'foo' foo()
#!/usr/bin/env python #coding:utf-8 def Before(request,kargs): print 'before' def After(request,kargs): print 'after' def Filter(before_func,after_func): def outer(main_func): def wrapper(request,kargs): before_result = before_func(request,kargs) if(before_result != None): return before_result; main_result = main_func(request,kargs) if(main_result != None): return main_result; after_result = after_func(request,kargs) if(after_result != None): return after_result; return wrapper return outer @Filter(Before, After) def Index(request,kargs): print 'index' if __name__ == '__main__': Index(1,2)