问题描述
我经常写如下代码
try:
self.title = item.title().content.string
except AttributeError, e:
self.title = None
有没有更快的方法来解决这个问题?单线?
Is there a quicker way of dealing with this? a one-liner?
推荐答案
item.title()
有哪些例外?光秃秃的 except
(可怕的做法!)并没有告诉我们.如果是 AttributeError(例如,item
没有 title
方法),
What exceptions are you getting from item.title()
? The bare except
(horrible practice!) doesn't tell us. If it's an AttributeError (where item
doesn't have a title
method, for example),
self.title = getattr(item, 'title', lambda: None)()
可能是您寻求的单线(但请注意,性能不会很大不同;-).
might be the one-liner you seek (but performance won't be enormously different, mind you;-).
编辑:由于 OP 完全改变了问题(它最初只是使用 self.title()
,现在使用 self.title().content.string
,并且确实专门捕获 AttributeError
而不是使用裸的 except
),这个答案的先前版本当然不再适用.现在正确的答案是:尝试单行是一种荒谬的方法,当属性引用链越来越长时(下一次会有多少,九个?因为他们从一跳到三)第一次编辑...;-).
Edit: as the OP entirely changed the question (it was originally just using self.title()
, it's now using self.title().content.string
, and does specifically catch AttributeError
rather than using a bare except
), the previous version of this answer of course doesn't apply any more. The proper answer now is: attempting a one-liner is an absurd approach, when the chain of attribute references &c keeps growing longer and longer (how many will there be next time, nine? Since they jumped from one to three with the first edit...;-).
并且不知道那么长的许多基本运算中的哪一个,德米特法则-嘲笑引用链可能会引发 AttributeError,任何优化尝试也将是盲目的.
And with no idea of which of the many elementary operations expressed by that long, Law of Demeter-scoffing chain of references might raise the AttributeError, any attempt at optimization would be flying rather blind, too.
这篇关于比“尝试"更快的方法和“除外"?- Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!