一、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 =
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 > else 'lt'
print result
a = lambda x,y:x+y
print a(,)

六、内置函数

 #print help()
print dir()
print vars()
#print type()
import temp
import temp
reload(temp)
id([])
#is
------------------
cmp(,)
cmp(,)
cmp(,)
cmp(,)
abs()
bool()
divmod()
max()
min()
sum()
pow(, )
------------------
len()
all()
any()
------------------
chr()
ord()
hex()
oct()
bin()
------------------
print range()
print xrange()
for i in xrange():
print i
for k,v in enumerate([,,,]):
print k,v
------------------
s= 'i am {0}'
print s.format('alex')
str()
------------------
def Function(arg):
print arg
print apply(Function,('aaaa')) #执行函数
print map(lambda x:x+,[,,]) #all
print filter(lambda x: x==,[,,]) #True序列
print reduce(lambda x,y:x+y,[,,]) #累加
x = [, , ]
y = [, , ]
z = [, , ]
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(,)
print random.randrange(,)

应用场景:生成随机验证码

import random
checkcode = ''
for i in range():
current = random.randrange(,)
if current != i:
temp = chr(random.randint(,))
else:
temp = random.randint(,)
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
#、时间戳 1970年1月1日之后的秒
#、元组 包含了:年、日、星期等... time.struct_time
#、格式化的字符串 -- : 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=)

6、sys

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

 9,lambda

08day03的更多相关文章

随机推荐

  1. VirtualBox AndroidX86 网络设置

    在Virtualbox中,把虚拟机网络设为“网络地址转换(NAT)”模式,高级中控制芯片(T)选择:PCnet-FAST III(Am79C973), 然后启动你的android-x86 4.0虚拟机 ...

  2. 以About Us为范例在Zen cart中增加页面

    1.在includes\languages\english\html_includes目录中新建文件define_about_us.php 2.在includes\templates\Your_tem ...

  3. java实现FTP下载文件

    ftp上传下载文件,是遵照ftp协议上传下载文件的,本例仅以下载文件为例. 重要的方法解释: 1.FTP功能相关依赖路径:org.apache.commons.net.ftp.*: 2.ftp默认端口 ...

  4. Andriod实现推送的解决方案(转)

    Andriod上实现消息推送的一般解决策略 第一种解决方案:C2DM云端推送功能 在Android手机平台上,Google提供了C2DM(Cloudto Device Messaging)服务,该服务 ...

  5. [转]loadrunner:系统的平均并发用户数和并发数峰值如何估算

    一.经典公式1: 一般来说,利用以下经验公式进行估算系统的平均并发用户数和峰值数据 1)平均并发用户数为 C = nL/T 2)并发用户数峰值 C‘ = C + 3*根号C C是平均并发用户数,n是l ...

  6. 特性(property)/静态方法(staticmethod)/类方法(classmethod)/__str__的用法

    property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值 1 import math 2 class Circle: 3 def __init__(self,radius): #圆的 ...

  7. Js 将 Date 转化为指定格式的String

    // 对Date的扩展,将 Date 转化为指定格式的String // 月(M).日(d).小时(h).分(m).秒(s).季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占 ...

  8. CF1137F Matches Are Not a Child's Play(LCT思维题)

    题目 CF1137F 很有意思的题目 做法 直接考虑带修改的做法,上一次最大值为u,这次修改v,则最大值为v了 我们发现:\(u-v\)这条链会留到最后,序列里的其他元素相对位置不变,这条链会\(u\ ...

  9. spring数据源、数据库连接池

    什么是数据源.数据库连接池? DataSource通常被称为数据源,它包含连接池和连接池管理两个部分,习惯上也经常把DataSource称为连接池. 数据库连接池的基本思想:为数据库连接建立一个“缓冲 ...

  10. DDOS防护原理

    1.常见DDoS攻击分类 DDoS粗略分类为流量型攻击和CC攻击.流量型攻击主要是通过发送报文侵占正常业务带宽,甚至堵塞整个数据中心的出口,导致正常用户访问无法达到业务服务器.CC攻击主要是针对某些业 ...