基于Flask实现后台权限管理系统 - 导言

网上有这样一个段子,在评论语言好坏的时候,都会有人评论说PHP是世界上最好的语言,人生苦短我用Python,这里姑且不去评论语言的好坏,每一个语言存在都有它的价值,譬如C语言适合底层开发,整个Linux操作系统几乎都是用C语言开发的,而像Go语言适合高并发的网络开发一样,并不是说像Go干不了其它事情,只是更适合某种应用场景。
谈到python之美,我认为这里有两个流派:python和pythonic。在我理解,Pythonic 就是很Python的Python代码,也就是用非常优美的python代码实现功能。举例说明:
我们要打开文件进行处理,在处理文件过程中可能会出错,但是,我们需要在处理文件出错的情况下,也顺利关闭文件。
传统风格的Python代码:

1 file= open(C:\data.txt')
2   try: for line in file: 
3     ...... 
4   finally: 
5      file.close()

 

Pythonic的代码:

1 with open(c:\data.txt') as file:
2   for line in file:
3     ......

 

通过with上下文管理,无需考虑资源释放问题以及异常情况下的资源释放问题,上下文管理器会帮你去处理。
再举一个例子:
字符串链接

1 names = ['1', '2', '3', '4', '5', '6', '7', '8'] 
2 s = names[0] for name in names[1:]:
3 s += ', ' + name print(s)

 

pythonic

1 print(', '.join(names))

 

可见pythonic的代码是如此的简洁和优雅。
具体更多的pythonic的代码,大家可以参考相关书籍,平时在学习和工作中注意积累。关于pythonic,这里不得不来一段python之禅,在python控制台下,输入:
import this
会显示下面内容:
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

中文意思如下:
Python之禅 by Tim Peters

优美胜于丑陋
明了胜于晦涩
简洁胜于复杂
复杂胜于凌乱
扁平胜于嵌套
间隔胜于紧凑
可读性很重要
即便假借特例的实用性之名,也不可违背这些规则
不要包容所有错误,除非你确定需要这样做
当存在多种可能,不要尝试去猜测
而是尽量找一种,最好是唯一一种明显的解决方案
虽然开始这并不容易,因为你不是Python之父
做也许好过不做,但不假思索就动手还不如不做
如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然
命名空间是一种绝妙的理念,我们应当多加利用

posted @ 2017-09-16 11:56  jeffrey.chu  阅读(2206)  评论(0编辑  收藏  举报

99code棋牌网