当前位置: 首页 > 后端技术 > Python

“应该知道”的Python函数和特性

时间:2023-03-26 15:38:38 Python

在使用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']-#编码["hello",42,[1,"two"],"apple"]-#解码[u'hello',42,[1,u'two'],u'apple']-这更紧凑,最重要的是与JavaScript和许多其他语言兼容。但是,对于复杂的对象,可能会丢失一些信息。05.压缩字符说到压缩,我们通常会想到文件,比如ZIP结构。在python中中电影长:导入zlibstring=“”“应该照顾疼痛本身,然后是脂肪宣传。现在,ipsumdolor。我想对那个伟大的学生进行教学。但是我不怕,但是拉西尼亚正在成长。但是,这很棒,除非柔软,柔软,否则很棒。非enim。Utmalesuadalacuseunullabibendumideuismodurnasodales。"""print"原始大小:{0}".format(len(string))compressed=zlib.compress(string)print"压缩后大小:{0}".format(len(compressed))decompressed=zlib.decompress(compressed)print"DecompressedSize:{0}".format(len(decompressed))#output#OriginalSize:1022#CompressedSize:423#DecompressedSize:102206有一个名为atexit的模块用于注册Shutdown函数,这允许您在脚本运行后立即执行一些代码如果你想在脚本执行结束时测量一些基准数据,比如运行了多长时间:importatexitimporttimeimportmathdefmicrotime(get_as_float=False):ifget_as_float:returntime.time()else:return'%f%d'%math.modf(time.time())start_time=microtime(False)atexit.register(start_time)defshutdown():globalstart_time打印“执行时间:{0}秒”.format(start_time)atexit.register(shutdown)#执行耗时:0.2970001387135607秒#atexit中的错误。_run_exitfuncs:#Traceback(最近一次调用):#文件“C:\Python27\lib\atexit.py”,第24行,在_run_exitfuncs#func(*targs,**kargs)#TypeError:'str'objectisnotcallable#errorinsys.exitfunc:#Traceback(mostrecentcalllast):#File"C:\Python27\lib\atexit.py",行24、在_run_exitfuncs#func(*targs,**kargs)#TypeError:'str'objectisnotcallable乍一看似乎很简单。只需在脚本的最底部添加代码,它就会在脚本结束前运行。但如果脚本中存在致命错误或脚本被用户终止,它可能不会运行。当你使用atexit.register()时,无论脚本停止运行的原因是什么,你的代码都会被执行。以上就是为大家整理的一些不常见的Python实用函数。大家有没有见过其他类似的功能,欢迎留言讨论。