来自分布在各处的开发tips
使用nametuple
nametuple用来构建只有少数属性但是没有方法的对象,比如数据库条目。
使用python的时候经常会出现这样的问题,我想构建一个很简单的类来进行测试,但是我不得不书写大量的代码,例如
class A: name = None num = None def __init__(self, name, num): self.name = name self.num = num def __str__(self): return '<A> name: {}, num: {}’.format(self.name, self.num)
然后才能进行创建。如果使用nametuples的话,这个例子会变成这样:
import collections A = collections.namedtuple(‘A', ['name', 'weight'])
这个时候代码量相对较少。
Python模仿Bash管道编程
这个用法十分有趣,重载|
操作符来完成这个操作。
Python中的try/except会在各种情况下被使用
def test(): try: print('test start') return except e as Exception: print(e) finally: print('test end')
输出
In [2]: test() test start test end

Python3 reload模块
>>> import spam >>> import imp >>> imp.reload(spam) <module 'spam' from './spam.py'> >>>
在一些代码进行修改之后,不想要重新打开shell,可以通过imp
进行模块的重载,具体的代码如上所示。
not not None
In [13]: a In [14]: not a Out[14]: True In [15]: not not a Out[15]: False In [16]: a = None In [17]: a In [18]: not a Out[18]: True In [19]: not not a Out[19]: False In [20]: not True Out[20]: False In [21]: not None Out[21]: True In [22]: not False Out[22]: True
使用 Pathlib 来操作路径相关的字符串
<未完待续>