美文网首页
Python 编程最佳实践

Python 编程最佳实践

作者: 艾尔温 | 来源:发表于2017-01-09 15:52 被阅读0次

项目结构定义: Sample Repository

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

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

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

Better

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

Best

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.

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

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

Good

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

Bad

# 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

# 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

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

相关文章

  • Python函数式编程

    在 Python 中使用函数式编程的最佳实践! 简 介 Python 是一种功能丰富的高级编程语言。它有通用的...

  • Python函数式编程

    在 Python 中使用函数式编程的最佳实践! 简 介 Python 是一种功能丰富的高级编程语言。它有通用的标准...

  • Python 编程最佳实践

    项目结构定义: Sample Repository This is what Kenneth Reitz reco...

  • jQuery编程的最佳实践

    jQuery编程的最佳实践 @(jquery)[jquery|最佳实践|编程规范] [TOC] 加载jQuery ...

  • Python高级编程.pdf

    【下载地址】 《Python高级编程》通过大量的实例,介绍了Python语言的最佳实践和敏捷开发方法,并涉及整个软...

  • 适合python基础学习的好书籍

    分享几本python基础学习的书籍给大家 《Python编程:从入门到实践》 《Python编程:从入门到实践》 ...

  • Python函数式编程最佳实践

    Python并非经典的FP(Functional Programming, 函数式编程)语言,用其原生的map/f...

  • Python最佳实践指南!

    Python最佳实践指南! 您好,地球人!欢迎来到Python最佳实践指南。 这是一份活着的、会呼吸的指南。 如果...

  • python编程 | 第一章 起步(环境搭建)

    python编程系统学习指路:快速学习 | python编程:从入门到实践 | Windows 1. python...

  • Python高性能编程PDF

    Python高性能编程电子版下载:下载链接 Python编程快速上手:链接 Python编程从入门到实践:链接 P...

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/kalhbttx.html