08day03

一、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')
            '''
    View Code

四、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

yield
View Code

 五、三元运算和lambda表达式

1 result = 'gt' if 1>3 else 'lt'
2     print result
1 a = lambda x,y:x+y
2     print a(4,10)
View Code

 六、内置函数

 1 #print help()
 2 print dir()
 3 print vars()
 4 #print type()
 5 import temp
 6 import temp
 7 reload(temp)
 8 id([12])
 9 #is
10 ------------------
11 cmp(2,3)
12 cmp(2,2)
13 cmp(2,1)
14 cmp(10,1)
15 abs()
16 bool()
17 divmod()
18 max()
19 min()
20 sum()
21 pow(2, 11)
22 ------------------
23 len()
24 all()
25 any()
26 ------------------
27 chr()
28 ord()
29 hex()
30 oct()
31 bin()
32 ------------------
33 print range(10)
34 print xrange(10)
35 for i in xrange(10):
36     print i
37 for k,v in enumerate([1,2,3,4]):
38     print k,v
39 ------------------
40 s= 'i am {0}'
41 print  s.format('alex')
42 str(1)
43 ------------------
44 def Function(arg):
45     print arg
46 print apply(Function,('aaaa')) #执行函数
47 print map(lambda x:x+1,[1,2,3]) #all
48 print filter(lambda x: x==1,[1,23,4]) #True序列
49 print reduce(lambda x,y:x+y,[1,2,3]) #累加
50 x = [1, 2, 3]
51 y = [4, 5, 6]
52 z = [4, 5, 6]
53 print zip(x, y,z)
54 ------------------
55 #__import__()
56 #hasattr()
57 #delattr()
58 #getattr()
59 module = __import__('temp')
60 print dir(module)
61 val = hasattr(module, 'version')
62 print val
63 ------------------
64 #callable()
65     #函数、类必须要有 __call__ 方法
66 #compile
67 #eval
68 com = compile('1+1','','eval')
69 print eval(com)
70 #exec语句
71 code = "for i in range(0, 10): print i"
72 cmpcode = compile(code, '', 'exec')
73 exec cmpcode
74 code = "print 1"
75 cmpcode = compile(code, '', 'single')
76 exec cmpcode
77 ------------------
78 #isinstance()
79 #issubclass()
80 #super()
81 #staticmethod()
View Code

更多,猛击这里

七、常用模块

1、random 用于生成随机数

1 import random
2 print random.random()
3 print random.randint(1,2)
4 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
View Code

2、md5 加密

 1 import md5
 2 hash = md5.new()
 3 hash.update('admin')
 4 print hash.hexdigest()
 5  
 6  
 7 import hashlib
 8 hash = hashlib.md5()
 9 hash.update('admin')
10 print hash.hexdigest()

3、序列化和json

4、re

  • compile
  • match search findall
  • group groups

正则表达式常用格式:

  字符:d w  . 

  次数:* + ? {m} {m,n}

5、time

 1 import time
 2 #1、时间戳    1970年1月1日之后的秒
 3 #3、元组 包含了:年、日、星期等... time.struct_time
 4 #4、格式化的字符串    2014-11-11 11:11
 5  
 6 print time.time()
 7 print time.mktime(time.localtime())
 8  
 9 print time.gmtime()    #可加时间戳参数
10 print time.localtime() #可加时间戳参数
11 print time.strptime('2014-11-11', '%Y-%m-%d')
12  
13 print time.strftime('%Y-%m-%d') #默认当前时间
14 print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间
15 print time.asctime()
16 print time.asctime(time.localtime())
17 print time.ctime(time.time())
18  
19 import datetime
20 '''
21 datetime.date:表示日期的类。常用的属性有year, month, day
22 datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
23 datetime.datetime:表示日期时间
24 datetime.timedelta:表示时间间隔,即两个时间点之间的长度
25 timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
26 strftime("%Y-%m-%d")
27 '''
28 import datetime
29 print datetime.datetime.now()
30 print datetime.datetime.now() - datetime.timedelta(days=5)
View Code

6、sys

 1 sys.argv           命令行参数List,第一个元素是程序本身路径
 2 sys.exit(n)        退出程序,正常退出时exit(0)
 3 sys.version        获取Python解释程序的版本信息
 4 sys.maxint         最大的Int值
 5 sys.maxunicode     最大的Unicode值
 6 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
 7 sys.platform       返回操作系统平台名称
 8 sys.stdout.write('please:')
 9 val = sys.stdin.readline()[:-1]
10 print val
View Code

 7、os

 1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
 2 os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
 3 os.curdir  返回当前目录: ('.')
 4 os.pardir  获取当前目录的父目录字符串名:('..')
 5 os.makedirs('dirname1/dirname2')    可生成多层递归目录
 6 os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
 7 os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
 8 os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
 9 os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
10 os.remove()  删除一个文件
11 os.rename("oldname","newname")  重命名文件/目录
12 os.stat('path/filename')  获取文件/目录信息
13 os.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
14 os.linesep    输出当前平台使用的行终止符,win下为"	
",Linux下为"
"
15 os.pathsep    输出用于分割文件路径的字符串
16 os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
17 os.system("bash command")  运行shell命令,直接显示
18 os.environ  获取系统环境变量
19 os.path.abspath(path)  返回path规范化的绝对路径
20 os.path.split(path)  将path分割成目录和文件名二元组返回
21 os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
22 os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
23 os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
24 os.path.isabs(path)  如果path是绝对路径,返回True
25 os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
26 os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
27 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
28 os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
29 os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
View Code

 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()
View Code
#!/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)
View Code

 9,lambda

原文地址:https://www.cnblogs.com/liyongsan/p/4974112.html