gpt4 book ai didi

python - Python中的EAFP原理是什么?

转载 作者:IT老高 更新时间:2023-10-28 21:05:32 26 4
gpt4 key购买 nike

在 Python 中“使用 EAFP 原则”是什么意思?你能提供任何例子吗?

最佳答案

来自 glossary :

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 and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

一个例子是尝试访问字典键。

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 版本必须在字典中搜索两次键,并且可能也被认为可读性稍差。

关于python - Python中的EAFP原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11360858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com