Python 程序员需要知道的 30 个技巧
这30个小技巧很有用!写程序越发优雅了,强烈推广!
贴士#9. 调试脚本
我们可以在 <pdb>
模块的帮助下在 Python 脚本中设置断点,下面是一个例子:
importpdb
pdb.set_trace()
我们可以在脚本中任何位置指定 <pdb.set_trace()>
并且在那里设置一个断点,相当简便。
贴士#13. 运行时检测 Python 版本
当正在运行的 Python 低于支持的版本时,有时我们也许不想运行我们的程序。为达到这个目标,你可以使用下面的代码片段,它也以可读的方式输出当前 Python 版本:
importsys
#Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
print("Sorry, you aren't running on Python 3.5n")
print("Please upgrade to 3.5.n")
sys.exit(1)
#Print Python version in a readable format.
print("Current Python version: ", sys.version)
或者你可以使用sys.version_info >= (3, 5)
来替换上面代码中的sys.hexversion != 50660080
,这是一个读者的建议。
在 Python 2.7 上运行的结果:
Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] onlinux Sorry, youaren't runningonPython 3.5 Pleaseupgradeto 3.5.
在 Python 3.5 上运行的结果:
Python 3.5.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] onlinux CurrentPythonversion: 3.5.2 (default, Aug 22 2016, 21:11:05) [GCC 5.3.0]
贴士#19. 使用
*
运算符(splat operator)来 unpack 函数参数
*
运算符(splat operator)提供了一个艺术化的方法来 unpack 参数列表,为清楚起见请参见下面的例子:
deftest(x, y, z): print(x, y, z) testDict = {'x': 1, 'y': 2, 'z': 3} testList = [10, 20, 30] test(*testDict) test(**testDict) test(*testList) #1-> x y z #2-> 1 2 3 #3-> 10 20 30贴士#20. 使用字典来存储选择操作
我们能构造一个字典来存储表达式:
stdcalc = { 'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y } print(stdcalc['sum'](9,3)) print(stdcalc['subtract'](9,3)) #1-> 12 #2-> 6