歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 你需要知道的、有用的 Python 功能和特點

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

日期:2017/3/1 9:49:37   编辑:Linux編程

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

帶任意數量參數的函數

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

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

  1. def function(arg1="",arg2=""):
  2. print"arg1: {0}".format(arg1)
  3. print"arg2: {0}".format(arg2)
  4. function("Hello", "World")
  5. # prints args1: Hello
  6. # prints args2: World
  7. function()
  8. # prints args1:
  9. # 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. foo()
  7. # Number of arguments: 0
  8. foo("hello")
  9. # Number of arguments: 1
  10. # Argument 0 is: hello
  11. foo("hello","World","Again")
  12. # Number of arguments: 3
  13. # Argument 0 is: hello
  14. # Argument 1 is: World
  15. # Argument 2 is: Again

使用Glob()查找文件

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

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

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

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

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

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

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

調試

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

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

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

生成唯一ID

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

  1. import uuid
  2. result = uuid.uuid1()
  3. print result
  4. # output => various attempts
  5. # 9e177ec0-65b6-11e3-b2d0-e4d53dfcf61b
  6. # be57b880-65b6-11e3-a04d-e4d53dfcf61b
  7. # 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. m = hashlib.sha1()
  6. m.update("The quick brown fox jumps over the lazy dog")
  7. print m.hexdigest()
  8. # c6e693d0b35805080632bc2469e1154a8d1072a86557778c27a01329630f8917
  9. # 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12

序列化

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

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

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

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

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

壓縮字符

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

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

注冊Shutdown函數

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

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

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

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

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

結論

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

Copyright © Linux教程網 All Rights Reserved