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

五、三元运算和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)

  

posted @ 2015-02-06 09:55  武沛齐  阅读(15265)  评论(3编辑  收藏  举报