Fork me on GitHub

Python 编程最佳实践

项目结构定义: Sample Repository

This is what Kenneth Reitz recommends.
This repository is available on GitHub.

1
2
3
4
5
6
7
8
9
10
11
README.rst
LICENSE
setup.py
requirements.txt
sample/__init__.py
sample/core.py
sample/helpers.py
docs/conf.py
docs/index.rst
tests/test_basic.py
tests/test_advanced.py

Very bad

1
2
3
4
[...]
from modu import *
[...]
x = sqrt(4) # Is sqrt part of modu? A builtin? Defined above?

Better

1
2
3
from modu import sqrt
[...]
x = sqrt(4) # sqrt may be part of modu, if not redefined in between

Best

1
2
3
import modu
[...]
x = modu.sqrt(4) # sqrt is visibly part of modu's namespace

Decorators

The Python language provides a simple yet powerful syntax called ‘decorators’. A decorator is a function or a class that wraps (or decorates) a function or a method. The ‘decorated’ function or method will replace the original ‘undecorated’ function or method. Because functions are first-class objects in Python, this can be done ‘manually’, but using the @decorator syntax is clearer and thus preferred.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def foo():
# do something
def decorator(func):
# manipulate func
return func
foo = decorator(foo) # Manually decorate
@decorator
def bar():
# Do something
# bar() is decorated

Bad

1
2
3
items = 'a b c d' # This is a string...
items = items.split(' ') # ...becoming a list
items = set(items) # ...and then a set

Good

1
2
3
4
count = 1
msg = 'a string'
def func():
pass # Do something


Bad

1
2
3
4
5
# create a concatenated string from 0 to 19 (e.g. "012..1819")
nums = ""
for n in range(20):
nums += str(n) # slow and inefficient
print nums

Good

1
2
3
4
5
# create a concatenated string from 0 to 19 (e.g. "012..1819")
nums = []
for n in range(20):
nums.append(str(n))
print "".join(nums) # much more efficient

Best

1
2
3
# create a concatenated string from 0 to 19 (e.g. "012..1819")
nums = [str(n) for n in range(20)]
print "".join(nums)

-------------本文结束感谢您的阅读-------------

本文标题:Python 编程最佳实践

文章作者:ElwinHe

发布时间:2017年10月08日 - 12:10

最后更新:2018年01月08日 - 22:01

原始链接:http://www.elwinhe.xyz/blog/cf66995.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。