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

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

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

你需要知道的、有用的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添加了對它的支持?,F在你可以使用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和許多其他語言兼容。然而對于復雜的對象,其中的一些信息可能丟失。

壓縮字符

當談起壓縮時我們通常想到文件,比如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特性很有用?請在評論處與我們分享。謝謝你的閱讀! 

責任編輯:龐桂玉 來源: Python開發者
相關推薦

2013-12-26 10:10:52

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

2018-05-30 15:15:47

混合云公共云私有云

2024-06-04 16:51:11

2019-10-23 10:36:46

DevSecOpsDevOps

2014-07-31 17:13:50

編碼程序員

2015-09-02 10:12:17

數據安全云存儲

2013-03-04 09:34:48

CSSWeb

2023-02-10 08:44:05

KafkaLinkedIn模式

2019-09-19 09:44:08

HTTPCDNTCP

2023-01-09 17:23:14

CSS技巧

2015-06-30 10:59:22

MobileWeb適配

2017-11-03 15:39:29

深度學習面試問答

2024-04-03 10:29:13

JavaScrip優化技巧

2022-06-07 14:38:40

云原生架構云計算
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 日韩欧美网 | 亚洲国产成人在线观看 | 欧美一级特黄aaa大片在线观看 | 亚洲欧美第一视频 | 欧美成人a | 国产亚洲精品久久情网 | 欧美日韩电影一区二区 | 最近中文字幕第一页 | 国产精品久久久久久久久久 | 国产精品大片 | 国产高清视频 | 成人黄色av网址 | 国产一区三区在线 | 国产精品福利在线观看 | 欧美日韩中文在线 | 免费人成在线观看网站 | 国产美女一区二区三区 | 国产成人精品一区二 | 日韩精品av一区二区三区 | 午夜影院黄 | 91黄在线观看 | 午夜免费精品视频 | 中文精品视频 | 黄a在线播放 | 久久久精品久久久 | 毛片免费看的 | 热久久久| julia中文字幕久久一区二区 | 色视频在线观看 | 亚洲欧美日韩激情 | 日韩一区二区在线视频 | 亚洲国产精品一区 | 日本欧美在线观看视频 | 国产精品久久久久久久岛一牛影视 | 午夜三级在线观看 | 久久综合国产 | 天天拍天天操 | 黄色成人亚洲 | 国产男人的天堂 | 国产小u女发育末成年 | 国产乱码精品一区二区三区忘忧草 |