Basic grammer
2019独角兽企业重金招聘Python工程师标准>>>
Usually used method
__name__
__file__
__doc__
Function
parameter
default parameter
variable parameter
return value
def Foo():print 'Foo'def Foo(arg)print argdef Foo(arg='tom'):print arg#must be put in the enddef Foo(arg1,arg2):print arg1,arg2Foo(arg2='alison',arg1='winne')def Foo(arg,*args):print arg,argsFoo('ray','neil','tom')def Foo(**kargs):print kargs.keys()print kargs.values()Foo(k1='sk',k2='alex')
Yield
def NeilReadlines():seek = 0while True:with open('E:/temp.txt','r') as f:f.seek(seek)data = f.readline()if data:seek = f.tell()yield dataelse:returnfor i in NeilReadlines():print i
Yield belongs to the decorative device
Three element operation and lambda expression
result = 'gt' if 1>3 else 'lt'
print result
a = lambda x,y:x+y
print a(4,10)
Built in function
for example:
#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')) #excute function
print map(lambda x:x+1,[1,2,3]) #all
print filter(lambda x: x==1,[1,23,4]) #True sequence
print reduce(lambda x,y:x+y,[1,2,3]) #accumulation
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()
#function、class must have "__call__" method
#compile
#eval
com = compile('1+1','','eval')
print eval(com)
#execute sentence
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()
More Click me
Popular Modules
first : random (usually used create random number)
for example:
import random
print random.random()
print random.randint(1,2)
print random.randrange(1,10)
Application scenarios: generating random verification code
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
second:md5 encryption
for example:
import md5
hash = md5.new()
hash.update('admin')
print hash.hexdigest()import hashlib
hash = hashlib.md5()
hash.update('admin')
print hash.hexdigest()
third:serialize and json
for example:
import pickledict = {"number1" : {"user" : "wang", "password" : "test123","lock" : "1"},\"number2" : {"user" : "yang", "password" : "test123","lock" : "2"}}#print dict["number1"]["user"]
#this is one way
p_str = pickle.dumps(dict) #this is serialize
print p_str
#this is two way
with open("e:/p_str.pk","w") as fp:pickle.dump(dict,fp)p_load = pickle.load("e:/p_str.pk")
print p_loadimport json
j_str = json.dumps(dict) #this is serialize
print j_str
#this is two way
with open("e:/j_str.json","w") as fp:json.dump(dict,fp)j_load = json.load("e:/j_str.json")
print j_load
fourth:re
for example:
compile
match search findall
group groups
regular expression format:
char:\d \w \t .
times:* + ? {m} {m,n}
fifth:time
import time
#1、time stamp Seconds after January 1, 1970
#3、The tuple contains: year, day, week, etc.... time.struct_time
#4、Formatted string 2014-11-11 11:11print time.time()
print time.mktime(time.localtime())print time.gmtime() #Additive time stamp parameter
print time.localtime() #Additive time stamp parameter
print time.strptime('2014-11-11', '%Y-%m-%d')print time.strftime('%Y-%m-%d') #Default current time
print time.strftime('%Y-%m-%d',time.localtime()) #Default current time
print time.asctime()
print time.asctime(time.localtime())
print time.ctime(time.time())import datetime
'''
datetime.date:represents date's class。Common attributes are:year, month, day
datetime.time:represents time's class。Common attributes are:hour, minute, second, microsecond
datetime.datetime:represents the date
datetime.timedelta:Represents the time interval, the length between the two time points.
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)
sixth:sys
sys.argv #Command line arguments List,The first element is the path of the program itself
sys.exit(n) #Exit the program, when the normal exit :exit(0)
sys.version #Gets the version information of the Python interpreter
sys.maxint
sys.maxunicode
sys.path #Returns the search path for the module,
#using the value of the PYTHONPATH environment variable at initialization time.
sys.platform
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]
print val
seventh: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所指向的文件或者目录的最后修改时间
eighth:Decorative device
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-8def 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 wrapperreturn outer@Filter(Before, After)
def Index(request,kargs):print 'index'if __name__ == '__main__':Index(1,2)
转载于:https://my.oschina.net/u/2393235/blog/668552
Basic grammer相关推荐
- 《THE BASIC GRAMMER OF C》
变量.常量及数据类型 变量 //写法不唯一也不完全 """声明变量(以int为数据类型进行列举)""" //Format:Type Name ...
- study notes for python
some useful materials Python完全新手教程 http://www.cnblogs.com/taowen/articles/11239.aspx (from taowen, B ...
- yacclex-Chapter1
参考资料 -<lex & yacc 2nd>:下载地址参考 http://blog.csdn.net/a_flying_bird/article/details/52486815 ...
- remote: HTTP Basic: Access denied
github 提交项目 提示 remote: HTTP Basic: Access denied 这个一般就是自己更改github账号的密码引起的 处理方法1 进入控制面板-->用户账号--&g ...
- PAT (Basic Level) Practise (中文)-1025. 反转链表 (25)
PAT (Basic Level) Practise (中文)-1025. 反转链表 (25) http://www.patest.cn/contests/pat-b-practise/1025 ...
- linux利用* vim提权,linux 通过suid vim.basic文件提权
在kali上复现 先给需要的vim.basic文件设置suid权限 chmod u+s /usr/bin/vim.basic 先adduser test1一个普通权限用户 现在就是一个合适的提权环境 ...
- android get请求最长字符,Android OKHTTP3的GET和POST方法(带basic auth)
使用前需要在Gradle Script中的build gradle中引入: compile 'com.squareup.okio:okio:1.13.0' compile 'com.squareup. ...
- PCLPCL/OpenNI tutorial 2: Cloud processing (basic)
翻译自:http://robotica.unileon.es/index.php/PCL/OpenNI_tutorial_2:_Cloud_processing_(basic)#Feature_est ...
- 在 Visual Basic .NET 或 JScript 代码中使用早期绑定
以往,开发人员喜欢使用 Visual Basic.VBScript 和 JScript 的原因之一就是它们所谓"无类型"的性质.变量不需要显式类型声明,并能够简单地通过使用来创建它 ...
最新文章
- python3.7入门教程-python 3.7极速入门教程6文件处理
- 一个电脑白痴与黑客的对话
- QNX设置开机启动命令来修改IP地址
- go语言中map的使用
- 干货 | BBR及其在实时音视频领域的应用
- 【小白学习C++ 教程】二十、C++ 中的auto关键字
- [翻译]NUnit---Explicit and Ignore Attributes(十二)
- 二、Linux常用命令——文件处理命令
- java 获取class的方法_[Java教程]Java反射定义、获取Class三种方法
- DTcms二次开发心得
- GPS NMEA协议,0183 定位数据格式 	双模定位:GNXXX GPS+BD 完整版
- TeamViewer 被发现用于(检测为)商业用途解决方案(亲测有效 )
- java uclinux_Java在基于uclinux的嵌入式系统中的应用
- MPB:南土所褚海燕组-​​利用种分布模型绘制微生物分布图谱
- 【VMware】Assuming drive cache: write through
- matlab工具箱及应用 pdf,matlab工具箱中文.pdf
- 计算机科学与技术统考专业代码,考试类别和级别及专业及科目代码表.doc
- 文件压缩zip(浏览器下载)
- 欧框语言框架标准C2,雅思成绩与欧洲语言共同参考框架的对应关系
- tring转换成Integer numberformatexception 分析