使用Python多年后,我偶然发现了一些我们过去不知道的函数和特性。有些可以说非常有用,但未得到充分利用。考虑到这一点,我整理了一些您应该了解的Python特性。具有任意数量参数的函数您可能已经知道Python允许您定义可选参数。但是还有另一种方法可以定义具有任意数量参数的函数。首先,看下面是一个只定义可选参数的例子deffunction(arg1="",arg2=""):print"arg1:{0}".format(arg1)print"arg2:{0}".format(arg2)function("Hello","World")#printsargs1:Hello#printsargs2:Worldfunction()#printsargs1:#printsargs2:现在,让我们看看如何定义一个可以接受任意参数的函数。我们使用元组来做到这一点。defffoo(*args):#justuse"*"tocollectallremainingargumentsintoatuplenumargs=len(args)print"Numberofarguments:{0}".format(numargs)fori,xinenumerate(args):print"参数{0}是:{1}"。format(i,x)foo()#Numberofarguments:0foo("hello")#Numberofarguments:1#Argument0is:hellofoo("hello","World","Again")#Numberofarguments:3#Argument0is:hello#Argument1is:World#Argument2is:再次使用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"):#addasmanyfiletypearguementsprintfilename#output#=========##test.txt#arg.py#g.py#shut.py#test.py如果想得到每个文件的绝对路径,可以在返回值上调用realpath()函数:importitertoolsasit,glob,osdefmultiple_file_types(*patterns):return.chain.from_iterable(glob.glob(pattern)forpatterninpatterns)forfilenameinmultiple_file_types("*.txt","*.py"):#addasmanyfiletypearguementsrealpath=os.path。realpath(文件名)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.pydebug以下示例使用检查模块。此模块可用于调试目的,并且具有比此处描述的更多的功能。本文不会涵盖此模块的所有细节,但会向您展示一些用例。importlogging,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,索引=\inspect.getouterframes(inspect.currentframe())[1]print(frame,filename,line_number,function_name,lines,index)test()#Shouldprintthefollowing(withcurrentdate/timeofcourse)#10-1919:57INFOtest.py:9:Someinformation#10-1919:57WARNINGtest.py:10:Ashotacrossthebow#(,'C:/xxx/pyfunc/magic.py',16,'',['test()\n'],0)生成唯一的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你可能会注意到,即使字符串是唯一的,但它们后面的几个字符看起来很相似。这是因为生成的字符串与计算机的MAC地址相关联。为了减少重复,您可以使用这两个函数。importhmac,hashlibkey='1'data='a'printhmac.new(key,data,hashlib.sha256).hexdigest()m=hashlib.sha1()m.update("Thequickbrownfoxjumpsoverthelazydog")printm.hexdigest()#c6e693d0b35805080632bc2469e1154a8d1072a82c591730#2fd4e1c67a2d28fced849ee1bb76e7391b93eb12序列化您是否曾需要将复杂变量存储在数据库或文本文件中?您不需要想出一种奇特的方法来将数组或对象格转换为格式化字符串,因为Python已经提供了此功能。importpicklevariable=['hello',42,[1,'two'],'apple']#serializecontentfile=open('serial.txt','w')serialized_obj=pickle.dumps(variable)file.write(serialized_obj)file.close()#unserializetoproduceoriginalcontenttarget=open('serial.txt','r')myObj=pickle.load(target)printserialized_objprintmyObj#output#(lp0#S'hello'#p1#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(变量)打印“编码{0}-{1}”.format(编码,类型(编码))#deccodingdecoded=json.loads(编码)打印“解码{0}-{1}”.format(解码,类型(解码))#output#Original['hello',42,[1,'two'],'apple']-
