成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

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

開發 后端
在使用Python多年以后,我偶然發現了一些我們過去不知道的功能和特性。一些可以說是非常有用,但卻沒有充分利用。考慮到這一點,我編輯了一些的你應該了解的Pyghon功能特色。

在使用Python多年以后,我偶然發現了一些我們過去不知道的功能和特性。一些可以說是非常有用,但卻沒有充分利用。考慮到這一點,我編輯了一些的你應該了解的Pyghon功能特色。

帶任意數量參數的函數

你可能已經知道了Python允許你定義可選參數。但還有一個方法,可以定義函數任意數量的參數。

首先,看下面是一個只定義可選參數的例子

  1. def function(arg1="",arg2=""): 
  2.         print "arg1: {0}".format(arg1) 
  3.         print "arg2: {0}".format(arg2) 
  4.        
  5.     function("Hello""World"
  6.     # prints args1: Hello 
  7.     # prints args2: World 
  8.        
  9.     function() 
  10.     # prints args1: 
  11.     # prints args2: 

現在,讓我們看看怎么定義一個可以接受任意參數的函數。我們利用元組來實現。

  1. def foo(*args): # just use "*" to collect all remaining arguments into a tuple 
  2.         numargs = len(args) 
  3.         print "Number of arguments: {0}".format(numargs) 
  4.         for i, x in enumerate(args): 
  5.             print "Argument {0} is: {1}".format(i,x) 
  6.        
  7.     foo() 
  8.     # Number of arguments: 0 
  9.        
  10.     foo("hello"
  11.     # Number of arguments: 1 
  12.     # Argument 0 is: hello 
  13.        
  14.     foo("hello","World","Again"
  15.     # Number of arguments: 3 
  16.     # Argument 0 is: hello 
  17.     # Argument 1 is: World 
  18.     # Argument 2 is: Again 

使用Glob()查找文件

大多Python函數有著長且具有描述性的名字。但是命名為glob()的函數你可能不知道它是干什么的除非你從別處已經熟悉它了。

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

  1. import glob 
  2.        
  3.     # get all py files 
  4.     files = glob.glob('*.py'
  5.     print files 
  6.        
  7.     # Output 
  8.     # ['arg.py', 'g.py', 'shut.py', 'test.py'] 

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

  1. import itertools as it, glob 
  2.    
  3. def multiple_file_types(*patterns): 
  4.     return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns) 
  5.    
  6. for filename in multiple_file_types("*.txt""*.py"): # add as many filetype arguements 
  7.     print filename 
  8.    
  9. # output 
  10. #=========# 
  11. # test.txt 
  12. # arg.py 
  13. # g.py 
  14. # shut.py 
  15. # test.py 

如果你想得到每個文件的絕對路徑,你可以在返回值上調用realpath()函數:

  1.     import itertools as it, glob, os 
  2.  
  3. def multiple_file_types(*patterns): 
  4. return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns) 
  5.        
  6. for filename in multiple_file_types("*.txt""*.py"): # add as many filetype arguements 
  7.  realpath = os.path.realpath(filename) 
  8. print realpath 
  9.        
  10. # output 
  11. #=========# 
  12. # C:\xxx\pyfunc\test.txt 
  13. # C:\xxx\pyfunc\arg.py 
  14. # C:\xxx\pyfunc\g.py 
  15. # C:\xxx\pyfunc\shut.py 
  16. # C:\xxx\pyfunc\test.py 

調試

下面的例子使用inspect模塊。該模塊用于調試目的時是非常有用的,它的功能遠比這里描述的要多。

這篇文章不會覆蓋這個模塊的每個細節,但會展示給你一些用例。

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

生成唯一ID

在有些情況下你需要生成一個唯一的字符串。我看到很多人使用md5()函數來達到此目的,但它確實不是以此為目的。
其實有一個名為uuid()的Python函數是用于這個目的的。

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

你可能會注意到,即使字符串是唯一的,但它們后邊的幾個字符看起來很相似。這是因為生成的字符串與電腦的MAC地址是相聯系的。

為了減少重復的情況,你可以使用這兩個函數。

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

序列化

你曾經需要將一個復雜的變量存儲在數據庫或文本文件中吧?你不需要想一個奇特的方法將數組或對象格轉化為式化字符串,因為Python已經提供了此功能。

  1. import pickle 
  2.    
  3. variable = ['hello'42, [1,'two'],'apple'
  4.        
  5.     # serialize content 
  6.     file = open('serial.txt','w'
  7. serialized_obj = pickle.dumps(variable) 
  8.     file.write(serialized_obj) 
  9. file.close() 
  10.  
  11. # unserialize to produce original content 
  12. target = open('serial.txt','r'
  13. myObj = pickle.load(target) 
  14.    
  15. print serialized_obj 
  16. print myObj 
  17.    
  18. #output 
  19. # (lp0 
  20. # S'hello' 
  21. # p1 
  22. # aI42 
  23. # a(lp2 
  24. # I1 
  25. # aS'two' 
  26. # p3 
  27. # aaS'apple' 
  28. # p4 
  29. # a. 
  30. # ['hello', 42, [1, 'two'], 'apple'] 

這是一個原生的Python序列化方法。然而近幾年來JSON變得流行起來,Python添加了對它的支持。現在你可以使用JSON來編解碼。

  1.     import json 
  2.        
  3.     variable = ['hello'42, [1,'two'],'apple'
  4. print "Original {0} - {1}".format(variable,type(variable)) 
  5.        
  6.     # encoding 
  7.     encode = json.dumps(variable) 
  8.     print "Encoded {0} - {1}".format(encode,type(encode)) 
  9.    
  10.     #deccoding 
  11.     decoded = json.loads(encode) 
  12.     print "Decoded {0} - {1}".format(decoded,type(decoded)) 
  13.    
  14. # output 
  15.    
  16. # Original ['hello', 42, [1, 'two'], 'apple'] - <type 'list'=""> 
  17. # Encoded ["hello", 42, [1, "two"], "apple"] - <type 'str'=""> 
  18. # Decoded [u'hello', 42, [1, u'two'], u'apple'] - <type 'list'=""> 

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

壓縮字符

當談起壓縮時我們通常想到文件,比如ZIP結構。在Python中可以壓縮長字符,不涉及任何檔案文件。

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

注冊Shutdown函數

有可模塊叫atexit,它可以讓你在腳本運行完后立馬執行一些代碼。

假如你想在腳本執行結束時測量一些基準數據,比如運行了多長時間:

  1. import atexit 
  2. import time 
  3. import math 
  4.    
  5. def microtime(get_as_float = False) : 
  6.     if get_as_float: 
  7.         return time.time() 
  8.     else
  9.         return '%f %d' % math.modf(time.time()) 
  10. start_time = microtime(False
  11. atexit.register(start_time) 
  12.    
  13. def shutdown(): 
  14.     global start_time 
  15.     print "Execution took: {0} seconds".format(start_time) 
  16.    
  17. atexit.register(shutdown) 
  18.    
  19. # Execution took: 0.297000 1387135607 seconds 
  20. # Error in atexit._run_exitfuncs: 
  21. # Traceback (most recent call last): 
  22. #   File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs 
  23. #     func(*targs, **kargs) 
  24. # TypeError: 'str' object is not callable 
  25. # Error in sys.exitfunc: 
  26. # Traceback (most recent call last): 
  27. #   File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs 
  28. #     func(*targs, **kargs) 
  29. # TypeError: 'str' object is not callable 

打眼看來很簡單。只需要將代碼添加到腳本的最底層,它將在腳本結束前運行。但如果腳本中有一個致命錯誤或者腳本被用戶終止,它可能就不運行了。

當你使用atexit.register()時,你的代碼都將執行,不論腳本因為什么原因停止運行。

結論

你是否意識到那些不是廣為人知Python特性很有用?請在評論處與我們分享。謝謝你的閱讀!

原文鏈接:http://www.oschina.net/translate/python-functions

責任編輯:陳四芳 來源: 開源中國編譯
相關推薦

2017-06-06 10:50:09

Python功能和特點

2020-03-27 12:30:39

python開發代碼

2011-09-20 10:56:35

云計算PaaS

2018-09-10 09:26:33

2022-04-29 09:00:00

Platform架構內核線程

2022-08-10 09:03:35

TypeScript前端

2021-09-01 09:00:00

開發框架React 18

2014-07-31 17:13:50

編碼程序員

2018-05-30 15:15:47

混合云公共云私有云

2024-06-04 16:51:11

2019-10-23 10:36:46

DevSecOpsDevOps

2015-09-02 10:12:17

數據安全云存儲

2017-11-03 15:39:29

深度學習面試問答

2024-04-03 10:29:13

JavaScrip優化技巧

2022-06-07 14:38:40

云原生架構云計算

2022-07-07 09:00:17

TCP 連接HTTP 協議

2019-01-24 08:19:17

云服務多云云計算

2022-08-05 11:03:59

TCP 四次揮手三次握手

2023-04-17 16:37:14

2013-03-04 09:34:48

CSSWeb
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 特黄色一级毛片 | 亚洲福利一区 | 午夜爽爽爽男女免费观看影院 | 99久久精品国产一区二区三区 | 亚洲一区免费 | 日韩在线观看一区 | 亚洲欧美激情精品一区二区 | 亚洲一区二区三区四区五区中文 | 日韩视频一区在线观看 | 国产精品福利网站 | 一级大片 | 成人一区二区电影 | 色噜噜色综合 | 国产91精品久久久久久久网曝门 | 国产三级国产精品 | 久久国产精品视频 | 亚洲天堂中文字幕 | 久久久久一区 | www.久久 | 成人中文字幕av | 中文字幕第二十页 | 免费在线播放黄色 | 成人午夜精品 | 在线观看视频91 | 麻豆亚洲 | 国产午夜精品一区二区三区 | 欧美日韩91| 日韩欧美视频 | 亚洲免费观看 | 国产精品久久久久久妇女6080 | 久久免费看 | 亚洲97| 美女国内精品自产拍在线播放 | 欧美精品久久 | 国产精品久久久久久久久免费樱桃 | 久久国产亚洲 | 在线看亚洲| 国产一区二区三区四区五区3d | 成人免费淫片aa视频免费 | 久久久国产精品 | 成人精品一区二区 |