不要使用索引来循环序列
不要:
for i in range(len(tab)) :
print tab[i]
做:
for elem in tab :
print elem
For 将为您自动执行大多数迭代操作。
如果您确实需要索引和元素,请使用enumerate。
for i, elem in enumerate(tab):
print i, elem
使用“==”检查True或False时要小心
if (var == True) :
# this will execute if var is True or 1, 1.0, 1L
if (var != True) :
# this will execute if var is neither True nor 1
if (var == False) :
# this will execute if var is False or 0 (or 0.0, 0L, 0j)
if (var == None) :
# only execute if var is None
if var :
# execute if var is a non-empty string/list/dictionary/tuple, non-0, etc
if not var :
# execute if var is "", {}, [], (), 0, None, etc.
if var is True :
# only execute if var is boolean True, not 1
if var is False :
# only execute if var is boolean False, not 0
if var is None :
# same as var == None
如果可以,不要检查,只要去做并处理错误
Python 爱好者通常会说“请求原谅比请求许可更容易”。
不要:
if os.path.isfile(file_path) :
file = open(file_path)
else :
# do something
做:
try :
file = open(file_path)
except OSError as e:
# do something
使用 python 2.6+ / 3 甚至更好:
with open(file_path) as file :
更好,因为它更通用。您可以将“try / except”应用于几乎任何事情。您无需关心如何防止它发生,只需关心您所冒的错误。
不要检查类型
Python 是动态类型的,因此检查类型会使您失去灵活性。相反,通过检查行为来使用鸭子类型。例如,您希望函数中有一个字符串,然后使用 str() 转换字符串中的任何对象。您期望一个列表,使用 list() 转换列表中的任何可迭代对象。
不要:
def foo(name) :
if isinstance(name, str) :
print name.lower()
def bar(listing) :
if isinstance(listing, list) :
listing.extend((1, 2, 3))
return ", ".join(listing)
做:
def foo(name) :
print str(name).lower()
def bar(listing) :
l = list(listing)
l.extend((1, 2, 3))
return ", ".join(l)
使用最后一种方式, foo 将接受任何对象。 Bar 将接受字符串、元组、集合、列表等等。便宜的干 :-)
不要混用空格和制表符
别这样。你会哭的。
使用 object 作为第一个父对象
这很棘手,但随着程序的增长,它会咬你一口。 Python 2.x 中有新旧类。旧的,嗯,旧的。它们缺乏一些特性,并且在继承时可能会出现尴尬的行为。为了可用,您的任何类都必须是“新样式”。为此,请使其继承自“对象”:
不要:
class Father :
pass
class Child(Father) :
pass
做:
class Father(object) :
pass
class Child(Father) :
pass
在 Python 3.x 中,所有类都是新样式,因此您可以声明 class Father: 就可以了。
不要在__init__方法之外初始化类属性
来自其他语言的人觉得这很诱人,因为您在 Java 或 PHP 中所做的工作。你写下类名,然后列出你的属性并给它们一个默认值。它似乎在 Python 中工作,然而,这并不像你想象的那样工作。
这样做将设置类属性(静态属性),然后当您尝试获取对象属性时,它将为您提供其值,除非它为空。在这种情况下,它将返回类属性。
这意味着两大危险:
- 如果更改类属性,则更改初始值。
- 如果您将可变对象设置为默认值,您将获得跨实例共享的相同对象。
不要(除非你想要静态):
class Car(object):
color = "red"
wheels = [wheel(), Wheel(), Wheel(), Wheel()]
做:
class Car(object):
def __init__(self):
self.color = "red"
self.wheels = [wheel(), Wheel(), Wheel(), Wheel()]