符合语言习惯的 Python 优雅编程技巧

  • 时间:
  • 浏览:2
  • 来源:大发5分快乐8APP下载_大发5分快乐8APP官方

pass##推荐from contextlib import ignored # Python 3 only

def getHour(self):return self.__hour

# do something... ##推荐 gen = (item for sl in nested_list if list_condition(sl) \

##推荐 navs = {}

本文作者:安生

# 许多文件操作...

def __getHour(self):return self.__hour

Python最大的优点之一但是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。要写出 Pythonic(优雅的、地道的、整洁的)代码,时需多就看学大牛们写的代码,github 上有全都非常优秀的源代码值得阅读,比如:requests、flask、tornado,下面列举许多常见的Pythonic写法。

##推荐 items = 'zero one two three'.split()

# do something for x, y, z

# Python 3 Only first, *middle, last = another_list

# method 2for i in range(len(items)):

##推荐 a, b = b, a # 先生成三个 元组(tuple)对象,但是unpack

##推荐import threading

1) Idiomatic Python:

“Programs must be written for people to read, and only incidentally for machines to execute.”

breakif found:

# do something if found... ##推荐if any(condition(item) for item in a_list):

http://python.net/~goodger/projects/pycon/4007/idiomatic/handout.html

##推荐 colors = ['red', 'blue', 'green', 'yellow']

lock.acquire()

# 多次判断 ##推荐if fruit in ["apple", "orange", "berry"]:

# ....if len(items) != 0:

# ...if items != []:

# do something for x & y ##推荐from itertools import product

# 使用 get 法子 navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]

# 使用 in 更加简洁

# 互斥操作...finally:

##推荐def my_range(n): i = 0

result = ''

# 互斥操作...

def setHour(self, hour):if 25 > hour > 0: self.__hour = hour

##推荐 new_list = [fn(item) for item in a_list if condition(item)]

# ... ##推荐if x:

##推荐from itertools import ifilter, imap

# ...

# 不可能 使用 setdefault 法子 navs.setdefault(portfolio, 0)

##推荐with open("some_file.txt") as f:

http://www.python.org/dev/peps/pep-0008/

# ...do something with d[key]

def my_range(n): i = 0

def __setHour(self, hour):if 25 > hour > 0: self.__hour = hour

2) PEP 8: Style Guide for Python Code:

原文发布时间为:2018-11-15

# do something if found...

with ignored(OSError):

# ....if items:

# ...do something with d[key] ##推荐if key in my_dict:

##推荐class Clock(object):def __init__(self): self.__hour = 1

# method 1 i = 0

class Clock(object):def __init__(self): self.__hour = 1

# my_dict[key] ...# 可以了当循环中时需更改key值的请况下,亲戚亲戚朋友时需使用 my_dict.keys()# 生成静态的键值列表。

# 许多文件操作..finally:

# my_dict[key] ... ##推荐for key in my_dict:

# do something...

##推荐 l = ['David', 'Pythonista', '+1-514-555-1234']

with lock: