自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

你需要知道的、有用的Python功能和特點(diǎn)

開發(fā) 后端
在使用Python多年以后,我偶然發(fā)現(xiàn)了一些我們過去不知道的功能和特性。一些可以說是非常有用,但卻沒有充分利用??紤]到這一點(diǎn),我編輯了一些你應(yīng)該了解的Python功能特色。

你需要知道的、有用的Python功能和特點(diǎn)

在使用Python多年以后,我偶然發(fā)現(xiàn)了一些我們過去不知道的功能和特性。一些可以說是非常有用,但卻沒有充分利用??紤]到這一點(diǎn),我編輯了一些你應(yīng)該了解的Python功能特色。

帶任意數(shù)量參數(shù)的函數(shù)

你可能已經(jīng)知道了Python允許你定義可選參數(shù)。但還有一個(gè)方法,可以定義函數(shù)任意數(shù)量的參數(shù)。

首先,看下面是一個(gè)只定義可選參數(shù)的例子

  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: 

現(xiàn)在,讓我們看看怎么定義一個(gè)可以接受任意參數(shù)的函數(shù)。我們利用元組來實(shí)現(xiàn)。

  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函數(shù)有著長且具有描述性的名字。但是命名為glob()的函數(shù)你可能不知道它是干什么的除非你從別處已經(jīng)熟悉它了。

它像是一個(gè)更強(qiáng)大版本的listdir()函數(shù)。它可以讓你通過使用模式匹配來搜索文件。

  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' 

你可以像下面這樣查找多個(gè)文件類型:

  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  

如果你想得到每個(gè)文件的絕對(duì)路徑,你可以在返回值上調(diào)用realpath()函數(shù):

  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  

調(diào)試

下面的例子使用inspect模塊。該模塊用于調(diào)試目的時(shí)是非常有用的,它的功能遠(yuǎn)比這里描述的要多。

這篇文章不會(huì)覆蓋這個(gè)模塊的每個(gè)細(xì)節(jié),但會(huì)展示給你一些用例。

  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

在有些情況下你需要生成一個(gè)唯一的字符串。我看到很多人使用md5()函數(shù)來達(dá)到此目的,但它確實(shí)不是以此為目的。

其實(shí)有一個(gè)名為uuid()的Python函數(shù)是用于這個(gè)目的的。

  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  

你可能會(huì)注意到,即使字符串是唯一的,但它們后邊的幾個(gè)字符看起來很相似。這是因?yàn)樯傻淖址c電腦的MAC地址是相聯(lián)系的。

為了減少重復(fù)的情況,你可以使用這兩個(gè)函數(shù)。

  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  

序列化

你曾經(jīng)需要將一個(gè)復(fù)雜的變量存儲(chǔ)在數(shù)據(jù)庫或文本文件中吧?你不需要想一個(gè)奇特的方法將數(shù)組或?qū)ο蟾褶D(zhuǎn)化為式化字符串,因?yàn)镻ython已經(jīng)提供了此功能。

  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' 

這是一個(gè)原生的Python序列化方法。然而近幾年來JSON變得流行起來,Python添加了對(duì)它的支持?,F(xiàn)在你可以使用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'] - <type 'list'=""
  32.  
  33. # Encoded ["hello", 42, [1, "two"], "apple"] - <type 'str'=""
  34.  
  35. # Decoded [u'hello', 42, [1, u'two'], u'apple'] - <type 'list'="" 

這樣更緊湊,而且最重要的是這樣與JavaScript和許多其他語言兼容。然而對(duì)于復(fù)雜的對(duì)象,其中的一些信息可能丟失。

壓縮字符

當(dāng)談起壓縮時(shí)我們通常想到文件,比如ZIP結(jié)構(gòu)。在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  

注冊(cè)Shutdown函數(shù)

有可模塊叫atexit,它可以讓你在腳本運(yùn)行完后立馬執(zhí)行一些代碼。

假如你想在腳本執(zhí)行結(jié)束時(shí)測量一些基準(zhǔn)數(shù)據(jù),比如運(yùn)行了多長時(shí)間:

  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  

打眼看來很簡單。只需要將代碼添加到腳本的***層,它將在腳本結(jié)束前運(yùn)行。但如果腳本中有一個(gè)致命錯(cuò)誤或者腳本被用戶終止,它可能就不運(yùn)行了。

當(dāng)你使用atexit.register()時(shí),你的代碼都將執(zhí)行,不論腳本因?yàn)槭裁丛蛲V惯\(yùn)行。

結(jié)論

你是否意識(shí)到那些不是廣為人知Python特性很有用?請(qǐng)?jiān)谠u(píng)論處與我們分享。謝謝你的閱讀! 

責(zé)任編輯:龐桂玉 來源: Python開發(fā)者
相關(guān)推薦

2013-12-26 10:10:52

Python

2020-03-27 12:30:39

python開發(fā)代碼

2011-09-20 10:56:35

云計(jì)算PaaS

2018-09-10 09:26:33

2022-04-29 09:00:00

Platform架構(gòu)內(nèi)核線程

2022-08-10 09:03:35

TypeScript前端

2021-09-01 09:00:00

開發(fā)框架React 18

2014-07-31 17:13:50

編碼程序員

2024-06-04 16:51:11

2018-05-30 15:15:47

混合云公共云私有云

2019-10-23 10:36:46

DevSecOpsDevOps

2015-09-02 10:12:17

數(shù)據(jù)安全云存儲(chǔ)

2020-04-27 08:31:29

單例模式Python軟件設(shè)計(jì)模式

2022-06-07 14:38:40

云原生架構(gòu)云計(jì)算

2022-08-05 11:03:59

TCP 四次揮手三次握手

2017-11-03 15:39:29

深度學(xué)習(xí)面試問答

2019-01-24 08:19:17

云服務(wù)多云云計(jì)算

2023-04-17 16:37:14

2022-07-07 09:00:17

TCP 連接HTTP 協(xié)議

2024-04-03 10:29:13

JavaScrip優(yōu)化技巧
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)