zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python开发系列课程(17) – Python“惯例”详解编程语言

Python编程语言开发 详解 &# 系列 8211 课程
2023-06-13 09:20:31 时间
Python“惯例”

“惯例”这个词指的是“习惯的做法,常规的办法,一贯的做法”,与这个词对应的英文单词叫“idiom”。由于Python跟其他很多编程语言在语法和使用上还是有比较显著的差别,因此作为一个Python开发者如果不能掌握这些惯例,就无法写出“Pythonic”的代码。下面我们总结了一些在Python开发中的惯用的代码。


owners = {1001: 骆昊, 1002: 王大锤} if name != and len(fruits) 0 and owners != {}: print(I love fruits!)

EAFP Easier to Ask Forgiveness than Permission.

LBYL Look Before You Leap.

好的代码:

d = {x: 5} 

try: 

 value = int(d[x]) 

 print(value) 

except (KeyError, TypeError, ValueError): 

 value = None

不好的代码:

d = {x: 5} 

if x in d and isinstance(d[x], str) / 

 and d[x].isdigit(): 

 value = int(d[x]) 

 print(value) 

else: 

 value = None

fruits = [orange, grape, pitaya, blueberry] 

for index, fruit in enumerate(fruits): 

print(index, :, fruit)

不好的代码:

fruits = [orange, grape, pitaya, blueberry] 

index = 0 

for fruit in fruits: 

 print(index, :, fruit) 

 index += 1