属性):
EAFP: 更容易要求宽恕比权限。这种常见的Python编码风格假定存在有效的键或属性,并且如果假设证明为假,则捕获异常。这种干净而快速的风格的特点是存在很多尝试和除了 陈述。该技术与常见的许多 其他语言LBYL风格如C.
这意味着,你的代码都遵循“官方” Python的方式,检查是否存在属性将Python的少形成鲜明对比。
然而,性能需求可以根据频哪里人对象将不具有id
属性最终会覆盖Python的考虑,因为引发异常需要更多的时间不是评估一个简单的条件。
考虑下面的代码:
import os
from timeit import timeit
def get_id_list_try(person):
try:
return [person.id]
except AttributeError:
return []
def get_id_list_if(person):
if hasattr(person, 'id'):
return [person.id]
else:
return []
class Person(object):
def __init__(self, id):
self.id = id
person_with_id = Person(1664)
person_no_id = object()
print("try with id: {}".format(
timeit("get_id_list_try(person_with_id)", number=1000000,
setup="from __main__ import get_id_list_try, person_with_id")))
print("try no id: {}".format(
timeit("get_id_list_try(person_no_id)", number=1000000,
setup="from __main__ import get_id_list_try, person_no_id")))
print("if with id: {}".format(
timeit("get_id_list_if(person_with_id)", number=1000000,
setup="from __main__ import get_id_list_if, person_with_id")))
print("if no id: {}".format(
timeit("get_id_list_if(person_no_id)", number=1000000,
setup="from __main__ import get_id_list_if, person_no_id")))
它测试的try/catch的性能,使用和不使用的id的if/else方法。它打印此:
try with id: 0.25232274121
try no id: 2.32747888986
if with id: 0.364873724104
if no id: 0.728008592266
正如你所看到的,try/catch方法有点快,当一个id存在;但是当id不存在时,if/else方法比try/catch方法快3倍。
的try-except块是完全符合Python。仅仅因为某些东西是单行的并不意味着它是实现它的最好方式。 –
在你提供的例子中不需要'getattr',使用'return [person.id]' –
如果Id是13,你想要'[13,]'? – Noelkd