def manual_str_formatting(name, subscribers):
if subscribers > 100000:
print("Wow " + name + “! you have " + str(subscribers) + " subscribers!”)
else:
print(“Lol " + name + " that’s not many subs”)
好的做法是使用 f-string,而且效率会更高:
def manual_str_formatting(name, subscribers):
better
if subscribers > 100000:
print(f"Wow {name}! you have {subscribers} subscribers!")
else:
print(f"Lol {name} that’s not many subs")
2、使用 finaly 而不是上下文管理器
坏的做法:
def finally_instead_of_context_manager(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.sendall(b’Hello, world’)
finally:
s.close()
好的做法是使用上下文管理器,即使发生异常,也会关闭 socket::
def finally_instead_of_context_manager(host, port):
close even if exception
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
s.sendall(b’Hello, world’)
3、尝试手动关闭文件
坏的做法:
def manually_calling_close_on_a_file(filename):
f = open(filename, “w”)
f.write(“hello!\n”)
f.close()
好的做法是使用上下文管理器,即使发生异常,也会自动关闭文件,凡是有上下文管理器的,都应该首先采用:
def manually_calling_close_on_a_file(filename):
with open(filename) as f:
f.write(“hello!\n”)
close automatic, even if exception
4、except 后面什么也不写
坏的做法:
def bare_except():
while True:
try:
s = input("Input a number: ")
x = int(s)
break
except: # oops! can’t CTRL-C to exit
print(“Not a number, try again”)
这样会捕捉所有异常,导致按下 CTRL-C 程序都不会终止,好的做法是
def bare_except():
while True:
try:
s = input("Input a number: ")
x = int(s)
break
except Exception: # 比这更好的是用 ValueError
print(“Not a number, try again”)
5、函数参数使用可变对象
如果函数参数使用可变对象,那么下次调用时可能会产生非预期结果,坏的做法
def mutable_default_arguments():
def append(n, l=[]):
l.append(n)
return l
l1 = append(0) # [0]
l2 = append(1) # [0, 1]
好的做法:
def mutable_default_arguments():
def append(n, l=None):
if l is None:
l = []
l.append(n)
return l
l1 = append(0) # [0]
l2 = append(1) # [1]
6、从不用推导式
坏的做法
squares = {}
for i in range(10):
squares[i] = i * i
好的做法
odd_squares = {i: i * i for i in range(10)}
7、推导式用的上瘾
推导式虽然好用,但是不可以牺牲可读性,坏的做法
c = [
sum(a[n * i + k] * b[n * k + j] for k in range(n))
for i in range(n)
for j in range(n)
]
好的做法:
c = []
for i in range(n):
for j in range(n):
ij_entry = sum(a[n * i + k] * b[n * k + j] for k in range(n))
c.append(ij_entry)
8、检查类型是否一致用 ==
坏的做法
def checking_type_equality():
Point = namedtuple(‘Point’, [‘x’, ‘y’])
p = Point(1, 2)
if type§ == tuple:
print(“it’s a tuple”)
else:
print(“it’s not a tuple”)
好的做法
def checking_type_equality():
Point = namedtuple(‘Point’, [‘x’, ‘y’])
p = Point(1, 2)
probably meant to check if is instance of tuple
if isinstance(p, tuple):
print(“it’s a tuple”)
else:
print(“it’s not a tuple”)
9、用 == 判断是否单例
坏的做法
def equality_for_singletons(x):
if x == None:
pass
if x == True:
pass
if x == False:
pass
好的做法
def equality_for_singletons(x):
better
if x is None:
pass
if x is True:
pass
if x is False:
pass
10、判断一个变量用 bool(x)
坏的做法
def checking_bool_or_len(x):
if bool(x):
pass
if len(x) != 0:
pass
好的做法
def checking_bool_or_len(x):
usually equivalent to
if x:
pass
11、使用类 C 风格的 for 循环
坏的做法
def range_len_pattern():
a = [1, 2, 3]
for i in range(len(a)):
v = a[i]
…
b = [4, 5, 6]
for i in range(len(b)):
av = a[i]
bv = b[i]
…
好的做法
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!