前言
文章有点标题党,主要是分享一些Python好用的语法糖,用更少的代码实现同样的功能,而且还很优雅。
123 | a = 1b = 2c = a > b ? a : b |
后来发现Python的if语句可以写成一行完成上述功能:
1 | c = a if a > b else b |
12345 | try: f = open(\’/path/to/file\’, \’r\’) print f.read()finally: if f: f.close() |
每次这样写太繁琐,来试试with的威力:
12 | with open(\’/path/to/file\’, \’r\’) as f: print f.read() |
代码更佳简洁,并且不必调用f.close()方法。
with利用了上下文管理协议,这玩意说起来太复杂,直接上代码。
自定义一个支持上下文管理协议的类, 类中实现enter方法和exit方法。
12345678910111213141516171819202122 | class MyWith(object): def __enter__(self): print \”Enter with\” return self # 返回对象给as后的变量 def __exit__(self, exc_type, exc_value, exc_traceback): #关闭资源等 if exc_traceback is None: print \”Exited without Exception\” return True else: print \”Exited with Exception\” return Falsedef test_with(): with MyWith() as my_with: print \”running my_with\” print \”——分割线—–\” with MyWith() as my_with: print \”running before Exception\” raise Exception print \”running after Exception\”if __name__ == \’__main__\’: test_with() |
输出:
1234567 | Enter withrunning my_withExited without Exception———分割线——–Enter withrunning before ExceptionExited with Exception |
map(func,seq)
,对seq中的每个元素进行操作,具体什么操作在func里定义。
1܌有三目运算符的语言会这样写:
map(func,seq) ,对seq中的每个元素进行操作,具体什么操作在func里定义。我们以前是这么写for循环的:
|
下一篇:Python 代码调试技巧