if form.admirer_or_model == "model":
model_form_css_style = Noneadmirer_or_model可能不存在于表单中,表单可能为空。
处理这种情况的最优雅的方法是什么?
发布于 2017-08-24 12:04:27
您可以使用getattr,将一个哨位值作为默认值传递:
if getattr(form, 'admirer_or_model', form) == "model":
...在Python实现https://en.wikipedia.org/wiki/Safe_navigation_operator之前,上面的内容就可以了。
发布于 2017-08-24 12:26:02
有很多可能的选择。哪一个是最方便的,一般取决于如果发生错误,您的代码流应该更改多少。
- don't do anything and it will raise an `AttributeError` in both cases:if form.admirer_or_model == "model":#在这两种情况下都会引发AttributeError,因为没有这样的属性,也没有<...>
- Handle the `AttributeError` - especially if both cases are to be handled the same: try:如果form.admirer_or_model == "model":<...>除了AttributeError作为e:<处理错误和退出,e.g.>引发TypeError(“form': " + e.message) # a common way to signal that #an argument failed a type and/or #a duck test - check as in the next suggestion, but without an<...>‘子句:
如果表单为空或不为hasattr(表单,'admirer_or_model'):
- check `if(form)` or `if(form is (not) None)` (if a valid `form` can evaluate to `False`) and `hasattr(form,'admirer_or_model')`, with `else` clause containing the alternative block:如果表单和hasattr(表单,'admirer_or_model'):否则:
-处理错误,但不要退出--特别是如果两种错误的处理都很常见的话:
试试: if form.admirer_or_model == "model":除了AttributeError作为e:
- use a ternary/other default-providing construct - e.g. `form if form else <default>` and `getattr(form,'admirer_or_model',<default>)`:if getattr( (表单如果是其他形式),'admirer_or_model',) == "model":<...>
还请注意,这些构造中的一些将错误处理块放在if块之前,并使用== "model",而有些则放在它之后。如果if块很大,这可能会在可读性方面产生影响:错误处理块最好放在靠近触发错误的行附近。
https://stackoverflow.com/questions/45861113
复制相似问题