看看这段代码:
>>> class c(object):
... pass
...
>>> a=c()
>>> if a.b.c:
... print 'hello'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'c' object has no attribute 'b'
安静的!这不是问题。请继续阅读:
当有人开发企业软件(例如使用 django)时,必须编写业务规则。这个规则看起来像
if invoice.customer.adress.country in ...:
invoice.makeSomeSpecialOffer()
但有时,表达所涉及的对象之一并不存在。然后,为了避免错误,我将句子改写为:
if invoice.customer and
invoice.customer.adress and
invoice.customer.adress.country and
invoice.customer.adress.country in ...
这可读性差!(您也可以尝试使用 hasattr 但可读性较差)。
我的工作是将 if 语句包含在 try 中,但是有一种更优雅或 pythatonic 的方式来避免这种错误?你最喜欢哪种技术?