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

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

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

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

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

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

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

  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: 

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

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

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

  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'] 

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

  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 

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

  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 

調(diào)試

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

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

  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

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

  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 

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

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

  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 

序列化

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

  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'] 

這是一個(gè)原生的Python序列化方法。然而近幾年來JSON變得流行起來,Python添加了對(duì)它的支持?,F(xiàn)在你可以使用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和許多其他語言兼容。然而對(duì)于復(fù)雜的對(duì)象,其中的一些信息可能丟失。

壓縮字符

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

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

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

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

  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 

打眼看來很簡單。只需要將代碼添加到腳本的最底層,它將在腳本結(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)論處與我們分享。謝謝你的閱讀!

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

責(zé)任編輯:陳四芳 來源: 開源中國編譯
相關(guān)推薦

2017-06-06 10:50:09

Python功能和特點(diǎn)

2020-03-27 12:30:39

python開發(fā)代碼

2011-09-20 10:56:35

云計(jì)算PaaS

2022-04-29 09:00:00

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

2022-08-10 09:03:35

TypeScript前端

2018-09-10 09:26:33

2021-09-01 09:00:00

開發(fā)框架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

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

2020-04-27 08:31:29

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

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適配

2019-01-24 08:19:17

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

2017-11-03 15:39:29

深度學(xué)習(xí)面試問答
點(diǎn)贊
收藏

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

主站蜘蛛池模板: 风间由美一区二区三区在线观看 | 国产欧美综合在线 | 国产福利在线看 | 国产一区二区不卡 | 久久综合伊人 | h视频在线观看免费 | 国产精品久久久久久久久久久久久久 | 国产成人精品一区二区 | 天天干视频在线 | 天天干狠狠操 | 人人色视频 | 色网站在线免费观看 | 午夜视频一区二区 | 好姑娘影视在线观看高清 | 精品国产一区二区三区av片 | 午夜影视网 | 精品不卡 | 91精品一区二区三区久久久久 | 九九精品在线 | 精品美女在线观看视频在线观看 | 一级无毛片 | 亚洲乱码国产乱码精品精98午夜 | 久久久久久中文字幕 | 午夜手机在线视频 | 91免费看片 | 亚洲一区二区在线播放 | 中文字幕国 | 欧美不卡在线 | 久久里面有精品 | 日韩av在线不卡 | 中国黄色毛片视频 | 亚洲精品丝袜日韩 | 91色视频在线观看 | 婷婷福利视频导航 | 99精品视频在线 | 久久精品在线免费视频 | 久久婷婷av| 91精品国产91久久久久久吃药 | 亚洲网在线 | 亚洲一区二区在线视频 | 看片网站在线 |