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

  • 时间:
  • 浏览:1
  • 来源:uu快3规律_uu快3下载地址_窍门

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

# method 1 i = 0

# ... ##推荐if x:

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

##推荐import threading

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

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

# ....if items:

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

##推荐 a, b = b, a # 先生成有1个元组(tuple)对象,就说 unpack

# ...do something with d[key]

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

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

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

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

1) Idiomatic Python:

# 某些文件操作...

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

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

# do something if found...

with lock:

# 互斥操作...finally:

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

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

# my_dict[key] ...# 不到当循环中需用更改key值的情况报告下,让我们歌词 歌词 需用使用 my_dict.keys()# 生成静态的键值列表。

# ...

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

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

2) PEP 8: Style Guide for Python Code:

# do something for x, y, z

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

# 可能性使用 setdefault 法律最好的办法 navs.setdefault(portfolio, 0)

lock.acquire()

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

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

本文作者:安生

##推荐 navs = {}

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

# 某些文件操作..finally:

##推荐from itertools import ifilter, imap

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

# do something...

# 使用 get 法律最好的办法 navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]

# 使用 in 更加简洁

# 互斥操作...

# ...if items != []:

result = ''

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

with ignored(OSError):

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

def my_range(n): i = 0

breakif found:

def __getHour(self):return self.__hour

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

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

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

def getHour(self):return self.__hour