在使用Python多年以后,我偶然发现了一些我们过去不知道的功能和特性。一些可以说是非常有用,但却没有充分利用。考虑到这一点,我编辑了一些你应该了解的Python功能特色。
带任意数量参数的函数
你可能已经知道了Python允许你定义可选参数。但还有一个方法,可以定义函数任意数量的参数。
首先,看下面是一个只定义可选参数的例子
def function(arg1="",arg2=""):
print "arg1: {0}".format(arg1)
print "arg2: {0}".format(arg2)
function("Hello", "World")
# prints args1: Hello
# prints args2: World
function()
# prints args1:
# prints args2:
现在,让我们看看怎么定义一个可以接受任意参数的函数。我们利用元组来实现
def foo(*args): # just use "*" to collect all remaining arguments into a tuple
numargs = len(args)
print "Number of arguments: {0}".format(numargs)
for i, x in enumerate(args):
print "Argument {0} is: {1}".format(i,x)
foo()
# Number of arguments: 0
foo("hello")
# Number of arguments: 1
# Argument 0 is: hello
foo("hello","World","Again")
# Number of arguments: 3
# Argument 0 is: hello
# Argument 1 is: World
# Argument 2 is: Again
使用Glob()查找文件
大多Python函数有着长且具有描述性的名字。但是命名为glob()的函数你可能不知道它是干什么的除非你从别处已经熟悉它了。
它像是一个更强大版本的listdir()函数。它可以让你通过使用模式匹配来搜索文件。
import glob
# get all py files
files = glob.glob('*.py')
print files
# Output
# ['arg.py', 'g.py', 'shut.py', 'test.py']
你可以像下面这样查找多个文件类型:
import itertools as it, glob
def multiple_file_types(*patterns):
return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements
print filename
# output
#=========#
# test.txt
# arg.py
# g.py
# shut.py
# test.py
如果你想得到每个文件的绝对路径,你可以在返回值上调用realpath()函数:
import itertools as it, glob, os
def multiple_file_types(*patterns):
return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements
realpath = os.path.realpath(filename)
print realpath
# output
#=========#
# C:\xxx\pyfunc\test.txt
# C:\xxx\pyfunc\arg.py
# C:\xxx\pyfunc\g.py
# C:\xxx\pyfunc\shut.py
# C:\xxx\pyfunc\test.py
调试
下面的例子使用inspect模块。该模块用于调试目的时是非常有用的,它的功能远比这里描述的要多。
这篇文章不会覆盖这个模块的每个细节,但会展示给你一些用例。
import logging, inspect
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(filename)s:%(lineno)-4d: %(message)s',
datefmt='%m-%d %H:%M',
)
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bow')
def test():
frame,filename,line_number,function_name,lines,index=\
inspect.getouterframes(inspect.currentframe())[1]
print(frame,filename,line_number,function_name,lines,index)
test()
# Should print the following (wiq |