你需要知道的、有用的Python功能和特点
创始人
2025-02-13 04:00:19
0

你需要知道的、有用的Python功能和特点

在使用Python多年以后,我偶然发现了一些我们过去不知道的功能和特性。一些可以说是非常有用,但却没有充分利用。考虑到这一点,我编辑了一些你应该了解的Python功能特色。

带任意数量参数的函数

你可能已经知道了Python允许你定义可选参数。但还有一个方法,可以定义函数任意数量的参数。

首先,看下面是一个只定义可选参数的例子

  1. def function(arg1="",arg2=""): 
  2.  
  3.     print "arg1: {0}".format(arg1) 
  4.  
  5.     print "arg2: {0}".format(arg2) 
  6.  
  7.   
  8.  
  9. function("Hello", "World") 
  10.  
  11. # prints args1: Hello 
  12.  
  13. # prints args2: World 
  14.  
  15.   
  16.  
  17. function() 
  18.  
  19. # prints args1: 
  20.  
  21. # prints args2: 

现在,让我们看看怎么定义一个可以接受任意参数的函数。我们利用元组来实现。

  1. def foo(*args): # just use "*" to collect all remaining arguments into a tuple 
  2.  
  3.     numargs = len(args) 
  4.  
  5.     print "Number of arguments: {0}".format(numargs) 
  6.  
  7.     for i, x in enumerate(args): 
  8.  
  9.         print "Argument {0} is: {1}".format(i,x) 
  10.  
  11.   
  12.  
  13. foo() 
  14.  
  15. # Number of arguments: 0 
  16.  
  17.   
  18.  
  19. foo("hello") 
  20.  
  21. # Number of arguments: 1 
  22.  
  23. # Argument 0 is: hello 
  24.  
  25.   
  26.  
  27. foo("hello","World","Again") 
  28.  
  29. # Number of arguments: 3 
  30.  
  31. # Argument 0 is: hello 
  32.  
  33. # Argument 1 is: World 
  34.  
  35. # Argument 2 is: Again  

使用Glob()查找文件

大多Python函数有着长且具有描述性的名字。但是命名为glob()的函数你可能不知道它是干什么的除非你从别处已经熟悉它了。

它像是一个更强大版本的listdir()函数。它可以让你通过使用模式匹配来搜索文件。

  1. import glob 
  2.  
  3.   
  4.  
  5. # get all py files 
  6.  
  7. files = glob.glob('*.py') 
  8.  
  9. print files 
  10.  
  11.   
  12.  
  13. # Output 
  14.  
  15. # ['arg.py', 'g.py', 'shut.py', 'test.py']  

你可以像下面这样查找多个文件类型:

  1. import itertools as it, glob 
  2.  
  3.   
  4.  
  5. def multiple_file_types(*patterns): 
  6.  
  7.     return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns) 
  8.  
  9.   
  10.  
  11. for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements 
  12.  
  13.     print filename 
  14.  
  15.   
  16.  
  17. # output 
  18.  
  19. #=========# 
  20.  
  21. # test.txt 
  22.  
  23. # arg.py 
  24.  
  25. # g.py 
  26.  
  27. # shut.py 
  28.  
  29. # test.py  

如果你想得到每个文件的绝对路径,你可以在返回值上调用realpath()函数:

  1. import itertools as it, glob, os 
  2.  
  3.   
  4.  
  5. def multiple_file_types(*patterns): 
  6.  
  7.     return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns) 
  8.  
  9.   
  10.  
  11. for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements 
  12.  
  13.     realpath = os.path.realpath(filename) 
  14.  
  15.     print realpath 
  16.  
  17.   
  18.  
  19. # output 
  20.  
  21. #=========# 
  22.  
  23. # C:\xxx\pyfunc\test.txt 
  24.  
  25. # C:\xxx\pyfunc\arg.py 
  26.  
  27. # C:\xxx\pyfunc\g.py 
  28.  
  29. # C:\xxx\pyfunc\shut.py 
  30.  
  31. # C:\xxx\pyfunc\test.py  

调试

下面的例子使用inspect模块。该模块用于调试目的时是非常有用的,它的功能远比这里描述的要多。

这篇文章不会覆盖这个模块的每个细节,但会展示给你一些用例。

  1. import logging, inspect 
  2.  
  3.   
  4.  
  5. logging.basicConfig(level=logging.INFO, 
  6.  
  7.     format='%(asctime)s %(levelname)-8s %(filename)s:%(lineno)-4d: %(message)s', 
  8.  
  9.     datefmt='%m-%d %H:%M', 
  10.  
  11.     ) 
  12.  
  13. logging.debug('A debug message') 
  14.  
  15. logging.info('Some information') 
  16.  
  17. logging.warning('A shot across the bow') 
  18.  
  19.   
  20.  
  21. def test(): 
  22.  
  23.     frame,filename,line_number,function_name,lines,index=\ 
  24.  
  25.         inspect.getouterframes(inspect.currentframe())[1] 
  26.  
  27.     print(frame,filename,line_number,function_name,lines,index) 
  28.  
  29.   
  30.  
  31. test() 
  32.  
  33.   
  34.  
  35. # Should print the following (with current date/time of course) 
  36.  
  37. #10-19 19:57 INFO     test.py:9   : Some information 
  38.  
  39. #10-19 19:57 WARNING  test.py:10  : A shot across the bow 
  40.  
  41. #(, 'C:/xxx/pyfunc/magic.py', 16, '', ['test()\n'], 0)  

生成唯一ID

在有些情况下你需要生成一个唯一的字符串。我看到很多人使用md5()函数来达到此目的,但它确实不是以此为目的。

其实有一个名为uuid()的Python函数是用于这个目的的。

  1. import uuid 
  2.  
  3. result = uuid.uuid1() 
  4.  
  5. print result 
  6.  
  7.   
  8.  
  9. # output => various attempts 
  10.  
  11. # 9e177ec0-65b6-11e3-b2d0-e4d53dfcf61b 
  12.  
  13. # be57b880-65b6-11e3-a04d-e4d53dfcf61b 
  14.  
  15. # c3b2b90f-65b6-11e3-8c86-e4d53dfcf61b  

你可能会注意到,即使字符串是唯一的,但它们后边的几个字符看起来很相似。这是因为生成的字符串与电脑的MAC地址是相联系的。

为了减少重复的情况,你可以使用这两个函数。

  1. import hmac,hashlib 
  2.  
  3. key='1' 
  4.  
  5. data='a' 
  6.  
  7. print hmac.new(key, data, hashlib.sha256).hexdigest() 
  8.  
  9.   
  10.  
  11. m = hashlib.sha1() 
  12.  
  13. m.update("The quick brown fox jumps over the lazy dog") 
  14.  
  15. print m.hexdigest() 
  16.  
  17.   
  18.  
  19. # c6e693d0b35805080632bc2469e1154a8d1072a86557778c27a01329630f8917 
  20.  
  21. # 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12  

序列化

你曾经需要将一个复杂的变量存储在数据库或文本文件中吧?你不需要想一个奇特的方法将数组或对象格转化为式化字符串,因为Python已经提供了此功能。

  1. import pickle 
  2.  
  3.   
  4.  
  5. variable = ['hello', 42, [1,'two'],'apple'] 
  6.  
  7.   
  8.  
  9. # serialize content 
  10.  
  11. file = open('serial.txt','w') 
  12.  
  13. serialized_obj = pickle.dumps(variable) 
  14.  
  15. file.write(serialized_obj) 
  16.  
  17. file.close() 
  18.  
  19.   
  20.  
  21. # unserialize to produce original content 
  22.  
  23. target = open('serial.txt','r') 
  24.  
  25. myObj = pickle.load(target) 
  26.  
  27.   
  28.  
  29. print serialized_obj 
  30.  
  31. print myObj 
  32.  
  33.   
  34.  
  35. #output 
  36.  
  37. # (lp0 
  38.  
  39. # S'hello' 
  40.  
  41. # p1 
  42.  
  43. # aI42 
  44.  
  45. # a(lp2 
  46.  
  47. # I1 
  48.  
  49. # aS'two' 
  50.  
  51. # p3 
  52.  
  53. # aaS'apple' 
  54.  
  55. # p4 
  56.  
  57. # a. 
  58.  
  59. # ['hello', 42, [1, 'two'], 'apple']  

这是一个原生的Python序列化方法。然而近几年来JSON变得流行起来,Python添加了对它的支持。现在你可以使用JSON来编解码。

  1. import json 
  2.  
  3.   
  4.  
  5. variable = ['hello', 42, [1,'two'],'apple'] 
  6.  
  7. print "Original {0} - {1}".format(variable,type(variable)) 
  8.  
  9.   
  10.  
  11. # encoding 
  12.  
  13. encode = json.dumps(variable) 
  14.  
  15. print "Encoded {0} - {1}".format(encode,type(encode)) 
  16.  
  17.   
  18.  
  19. #deccoding 
  20.  
  21. decoded = json.loads(encode) 
  22.  
  23. print "Decoded {0} - {1}".format(decoded,type(decoded)) 
  24.  
  25.   
  26.  
  27. # output 
  28.  
  29.   
  30.  
  31. # Original ['hello', 42, [1, 'two'], 'apple'] -  
  32.  
  33. # Encoded ["hello", 42, [1, "two"], "apple"] -  
  34.  
  35. # Decoded [u'hello', 42, [1, u'two'], u'apple'] -   

这样更紧凑,而且最重要的是这样与JavaScript和许多其他语言兼容。然而对于复杂的对象,其中的一些信息可能丢失。

压缩字符

当谈起压缩时我们通常想到文件,比如ZIP结构。在Python中可以压缩长字符,不涉及任何档案文件。

  1. import zlib 
  2.  
  3.   
  4.  
  5. string =  """   Lorem ipsum dolor sit amet, consectetur 
  6.  
  7.                 adipiscing elit. Nunc ut elit id mi ultricies 
  8.  
  9.                 adipiscing. Nulla facilisi. Praesent pulvinar, 
  10.  
  11.                 sapien vel feugiat vestibulum, nulla dui pretium orci, 
  12.  
  13.                 non ultricies elit lacus quis ante. Lorem ipsum dolor 
  14.  
  15.                 sit amet, consectetur adipiscing elit. Aliquam 
  16.  
  17.                 pretium ullamcorper urna quis iaculis. Etiam ac massa 
  18.  
  19.                 sed turpis tempor luctus. Curabitur sed nibh eu elit 
  20.  
  21.                 mollis congue. Praesent ipsum diam, consectetur vitae 
  22.  
  23.                 ornare a, aliquam a nunc. In id magna pellentesque 
  24.  
  25.                 tellus posuere adipiscing. Sed non mi metus, at lacinia 
  26.  
  27.                 augue. Sed magna nisi, ornare in mollis in, mollis 
  28.  
  29.                 sed nunc. Etiam at justo in leo congue mollis. 
  30.  
  31.                 Nullam in neque eget metus hendrerit scelerisque 
  32.  
  33.                 eu non enim. Ut malesuada lacus eu nulla bibendum 
  34.  
  35.                 id euismod urna sodales. """ 
  36.  
  37.   
  38.  
  39. print "Original Size: {0}".format(len(string)) 
  40.  
  41.   
  42.  
  43. compressed = zlib.compress(string) 
  44.  
  45. print "Compressed Size: {0}".format(len(compressed)) 
  46.  
  47.   
  48.  
  49. decompressed = zlib.decompress(compressed) 
  50.  
  51. print "Decompressed Size: {0}".format(len(decompressed)) 
  52.  
  53.   
  54.  
  55. # output 
  56.  
  57.   
  58.  
  59. # Original Size: 1022 
  60.  
  61. # Compressed Size: 423 
  62.  
  63. # Decompressed Size: 1022  

注册Shutdown函数

有可模块叫atexit,它可以让你在脚本运行完后立马执行一些代码。

假如你想在脚本执行结束时测量一些基准数据,比如运行了多长时间:

  1. import atexit 
  2.  
  3. import time 
  4.  
  5. import math 
  6.  
  7.   
  8.  
  9. def microtime(get_as_float = False) : 
  10.  
  11.     if get_as_float: 
  12.  
  13.         return time.time() 
  14.  
  15.     else: 
  16.  
  17.         return '%f %d' % math.modf(time.time()) 
  18.  
  19. start_time = microtime(False) 
  20.  
  21. atexit.register(start_time) 
  22.  
  23.   
  24.  
  25. def shutdown(): 
  26.  
  27.     global start_time 
  28.  
  29.     print "Execution took: {0} seconds".format(start_time) 
  30.  
  31.   
  32.  
  33. atexit.register(shutdown) 
  34.  
  35.   
  36.  
  37. # Execution took: 0.297000 1387135607 seconds 
  38.  
  39. # Error in atexit._run_exitfuncs: 
  40.  
  41. # Traceback (most recent call last): 
  42.  
  43. #   File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs 
  44.  
  45. #     func(*targs, **kargs) 
  46.  
  47. # TypeError: 'str' object is not callable 
  48.  
  49. # Error in sys.exitfunc: 
  50.  
  51. # Traceback (most recent call last): 
  52.  
  53. #   File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs 
  54.  
  55. #     func(*targs, **kargs) 
  56.  
  57. # TypeError: 'str' object is not callable  

打眼看来很简单。只需要将代码添加到脚本的***层,它将在脚本结束前运行。但如果脚本中有一个致命错误或者脚本被用户终止,它可能就不运行了。

当你使用atexit.register()时,你的代码都将执行,不论脚本因为什么原因停止运行。

结论

你是否意识到那些不是广为人知Python特性很有用?请在评论处与我们分享。谢谢你的阅读! 

相关内容

热门资讯

PHP新手之PHP入门 PHP是一种易于学习和使用的服务器端脚本语言。只需要很少的编程知识你就能使用PHP建立一个真正交互的...
各种千兆交换机的数据接口类型详... 千兆交换机有很多值得学习的地方,这里我们主要介绍各种千兆交换机的数据接口类型,作为局域网的主要连接设...
什么是大数据安全 什么是大数据... 在《为什么需要大数据安全分析》一文中,我们已经阐述了一个重要观点,即:安全要素信息呈现出大数据的特征...
如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
范例解读VB.NET获取环境变... VB.NET编程语言的使用范围非常广泛,可以帮助开发人员处理各种程序中的需求,而且还能对移动设备进行...
网络中立的未来 网络中立性是什... 《牛津词典》中对“网络中立”的解释是“电信运营商应秉持的一种原则,即不考虑来源地提供所有内容和应用的...
规避非法攻击 用好路由器远程管... 单位在市区不同位置设立了科技服务点,每一个服务点的员工都通过宽带路由器进行共享上网,和单位网络保持联...