在使用Python多年后,我偶然发现了一些我们以前不知道的函数和特性。有些可以说非常有用,但未得到充分利用。考虑到这一点,我整理了一些您应该了解的Python特性。00.具有任意数量参数的函数您可能已经知道Python允许您定义可选参数。但是还有另一种方法可以定义具有任意数量参数的函数。首先,查看以下仅定义可选参数的示例:deffunction(arg1="",arg2=""):print"arg1:{0}".format(arg1)print"arg2:{0}"。format(arg2)function("Hello","World")#printsargs1:Hello#printsargs2:Worldfunction()#printsargs1:#printsargs2:现在,让我们看看如何定义一个可以接受任意参数的函数。我们使用元组来做到这一点。deffoo(*args):#只需使用“*”将所有剩余参数收集到一个元组中numargs=len(args)print"Numberofarguments:{0}".format(numargs)fori,xinenumerate(args):print"Argument{0}is:{1}".format(i,x)foo()#Numberofarguments:0foo("hello")#Numberofarguments:1#Argument0is:hellofoo("hello","World","Again")#参数个数:3#参数0为:hello#参数1为:World#参数2为:Again补充:更通用的函数定义方式是deffun(args,kwargs),在很多Python源码中都可以找到这个定义,其中args代表任意数量的未命名参数,本质上是一个tuple元组;kwargs代表关键字参数,本质上是一个字典dict。01.使用Glob()查找文件大多数Python函数的名称都很长且具有描述性。但是名为glob()的函数您可能不知道它的作用,除非您已经从其他地方熟悉它。\它就像是listdir()函数的更强大版本。它允许您使用模式匹配来搜索文件。importglob#getallpyfilesfiles=glob.glob('*.py')printfiles#Output#['arg.py','g.py','shut.py','test.py']你可以像这样查找多个文件类型:importitertoolsasit,globdefmultiple_file_types(*patterns):returnit.chain.from_iterable(glob.glob(pattern)\forpatterninpatterns)forfilenameinmultiple_file_types("*.txt","*.py"):#添加尽可能多的文件类型参数printfilename#output#=========##test.txt#arg.py#g.py#shut.py#test.pyif如果你想得到每个文件的绝对路径,可以在返回值上调用realpath()函数:importitertoolsasit,glob,osdefmultiple_file_types(*patterns):returnit.chain.from_iterable(glob.glob(pattern)\forpatterninpatterns)forfilenameinmultiple_file_types("*.txt","*.py"):#添加尽可能多的文件类型参数realpath=os.path.realpath(filename)printrealpath#output#=========##C:\xxx\pyfunc\test.txt#C:\xxx\pyfunc\arg.py#C:\xxx\pyfunc\g.py#C:\xxx\pyfunc\shut.py#C:\xxx\pyfunc\test.py02。调试下面的示例使用了inspect模块,它对调试很有用,并且比这里描述的功能多得多。本文不会涵盖此模块的所有细节,但会向您展示一些用例。导入日志,inspectlogging.basicConfig(level=logging.INFO,format='%(asctime)s%(levelname)-8s%(filename)s:%(lineno)-4d:%(message)s',datefmt='%m-%d%H:%M',)logging.debug('Adebugmessage')logging.info('Someinformation')logging.warning('Ashotacrossthebow')deftest():frame,filename,line_number,function_name,lines,index=\inspect.getouterframes(inspect.currentframe())[1]print(frame,filename,line_number,function_name,lines,index)test()#应打印以下内容(与当前当然是日期/时间)#10-1919:57INFOtest.py:9:Someinformation#10-1919:57WARNINGtest.py:10:Ashotacrossthebow#(,'C:/xxx/pyfunc/magic.py',16,'',['test()\n'],0)03。生成一个唯一的ID在某些情况下,您需要生成一个唯一的字符串。我已经看到很多人为此目的使用md5()函数,但它确实不是为这个目的而设计的。\实际上有一个名为uuid()的Python函数用于此目的。importuuidresult=uuid.uuid1()printresult#output=>variousattempts#9e177ec0-65b6-11e3-b2d0-e4d53dfcf61b#be57b880-65b6-11e3-a04d-e4d53dfcf61b#c3b2b90f-65b6-11e3-8c86-e4d53dfcf61b你可能会注意Itturnsoutthateventhoughthestringsareunique,thenextfewcharacterslooksimilar.Thisisbecausethegeneratedstringisassociatedwiththecomputer'sMACaddress.Toreduceduplication,youcanusethesetwofunctions.importhmac,hashlibkey='1'data='a'printhmac.new(key,data,hashlib.sha256).hexdigest()m=hashlib.sha1()m.update("Thequickbrownfoxjumpsoverthelazydog")printm.hexdigest()#c6e693d0b35805080632bc2469e1154a8d1072a86557778c27a01329630f8917#2fd4e1c67a2d28fced849ee1bb76e7391b93eb12最近整理了一套编程学习资料分享给大家,全是干货内容,包含教程视频、电子书、源码笔记、学习路线图、实战项目、面试题等Wait,payattentiontogzh[Pythonprogramminglearningcircle]togetitforfree,justreplytothekeywords[learningmaterials],hurryup!04.SerializationHaveyoueverneededtostoreacomplexvariableinadatabaseortextfile?Youdon'tneedtothinkofafancywaytoconvertanarrayorobjectlatticeintoaformattedstring,becausePythonalreadyprovidesthisfunctionality.importpicklevariable=['hello',42,[1,'two'],'apple']#serializecontentfile=open('serial.txt','w')serialized_obj=pickle.dumps(variable)file.write(serialized_obj)file.close()#反序列化以生成原始内容aI42#a(lp2#I1#aS'two'#p3#aaS'apple'#p4#a.#['hello',42,[1,'two'],'apple']这是一个原生的Python序列化方法,不过近几年JSON开始流行,Python也加入了对它的支持,现在可以用JSON来编解码了。importjsonvariable=['hello',42,[1,'two'],'apple']print"Original{0}-{1}".format(variable,type(variable))#encodingencode=json.dumps(variable)print"Encoded{0}-{1}".format(encode,type(encode))#deccodingdecoded=json.loads(encode)print"Decoded{0}-{1}".format(decoded,type(解码))#输出#原始['hello',42,[1,'two'],'apple']-
