Basic grammer

Python编程技巧与应用实例
本文深入探讨了Python编程中的核心概念与实用技巧,通过详细解析常见函数与装饰器的用法,展示如何灵活运用Python解决实际问题。此外,文章还涵盖了Yield、Lambda表达式、内置函数、迭代操作等高级特性,以及数据结构、算法、测试工具等核心知识点,旨在为Python开发者提供全面的技术指南。

Usually used method

  • __name__

  • __file__

  • __doc__

Function

  • parameter

  • default parameter

  • variable parameter

  • return value

        def Foo():
            print 'Foo'
            
        def Foo(arg)
            print arg

        def Foo(arg='tom'):
            print arg
        #must be put in the end


        def Foo(arg1,arg2):
            print arg1,arg2
            
        Foo(arg2='alison',arg1='winne')

        def Foo(arg,*args):
            print arg,args
            
        Foo('ray','neil','tom')

        def Foo(**kargs):
            print kargs.keys()
            print kargs.values()
        Foo(k1='sk',k2='alex')

Yield

def NeilReadlines():
    seek = 0
    while True:
        with open('E:/temp.txt','r') as f:
            f.seek(seek)
            data = f.readline()
            if data:
                seek = f.tell()
                yield data
            else:
                return
            

for 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 pickle

dict = {"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_load

import 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:11
 
print 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-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)


转载于:https://my.oschina.net/u/2393235/blog/668552

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值