Python中的EAFP原理是什么? [英] What is the EAFP principle in Python?
问题描述
Python 中的使用 EAFP 原理"是什么意思?你能提供一些例子吗?
What is meant by "using the EAFP principle" in Python? Could you provide any examples?
推荐答案
来自 glossary:
请求原谅比许可更容易.这种常见的 Python 编码风格假设存在有效的键或属性,并在假设证明为假时捕获异常.这种干净而快速的风格的特点是存在许多try
和except
语句.该技术与许多其他语言(如 C)常见的 LBYL 风格形成对比.
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many
try
andexcept
statements. The technique contrasts with the LBYL style common to many other languages such as C.
一个例子是尝试访问字典键.
An example would be an attempt to access a dictionary key.
EAFP:
try:
x = my_dict["key"]
except KeyError:
# handle missing key
LBYL:
if "key" in my_dict:
x = my_dict["key"]
else:
# handle missing key
LBYL 版本必须在字典中搜索关键字两次,而且可能会被认为可读性稍差.
The LBYL version has to search the key inside the dictionary twice, and might also be considered slightly less readable.
这篇关于Python中的EAFP原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!