我是新来的Python,并试图了解了Pythonway® 我得到的EAFP原则,我喜欢它,但如何将它在这个例子中应用?
编辑:我只在乎没有儿童的财产,不是里面dosomethingwith发生了什么()项目。 在我EAFP的理解,我应该使用的可能是错误语句通常和捕获异常,但语句是在为,那么我不得不设法整个块。
try:
for child in item.children:
dosomethingwith( child )
except AttributeError:
""" did the exception come from item.children or from dosomethingwith()? """
做这样的事情,虽然看起来很像LBYL:
try:
item.children
except AttributeError:
""" catch it """
for child in item.children: ...
其实,当您要访问它可能无法提供的资源使用EAFP。 IMO,AttributeError
是一个坏榜样...
无论如何,你可以让缺少children
属性,并从AttributeError
功能提出了一个do_something_with()
之间的差异。你需要有两个异常处理程序:
try:
children = item.children
except AttributeError:
print("Missing 'children' attribute")
raise # re-raise
else:
for child in children:
try:
do_something_with(child)
except AttributeError:
print("raised from do_something_with()")
raise # re-raise
EAFP的一个典型的例子是make_dir_if_not_exist()
功能:
# LBYL
if not os.path.exists("folder"):
os.mkdir("folder")
# EAFP
try:
os.mkdir("folder")
except FileExistsError:
pass