处理可能为无的变量

编程入门 行业动态 更新时间:2024-10-27 08:28:35
本文介绍了处理可能为无的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

尽管这与Django有关,但实际上只是一个通用的编程效率问题。

Although this is django related, it's really just a general, programming efficiency question.

我有一个模板,根据情况,该模板将获取并返回一种或两种形式。如果返回一种形式,则保存第二种形式的变量将为None。

I have a template that, depending on the scenario, will get and return either one or two forms. If it returns one form, the variable that holds the second form will be None.

我需要检查这些形式是否有效。类似于我在网上阅读的示例,在相同的if语句中检查两种形式的.is_valid()。但这并不奇怪,如果第二种形式为None,则会抛出错误(NoneType对象没有属性is_valid)。

I need to check if the forms are valid. Similar to an example I read online, I'm checking .is_valid() on both forms in the same if statement. But this unsurprisingly throws an error (NoneType object has no attribute is_valid) if the second form is None.

什么是检查两种形式都为最佳的最佳方法是什么?如果第二个格式为None,则有效而不会导致错误?

if request.method == 'POST': form = form_dict[modelname][1](request.POST) try: form_two = form_dict[modelname][2](request.POST) except: form_two = None if form.is_valid() and form_two.is_valid(): # Do some stuff and save the data from the form(s) else: try: form = form_dict[modelname][1]() form_two = form_dict[modelname][2]() except: form_two = None

推荐答案

通常检查是否有东西是 None ..只需检查一下?

In the general case of checking if something is None.. just check it?

if x is not None and x.is_valid(): ...

在Python中,或和和都短路,表示在表达式 x和y 中,<如果 x 是 false ,则不会评估code> y (因为表达式不管 y 是什么,都是错误的。

In Python, or and and both short circuit, meaning that in the expression x and y, y is not evaluated if x is false (since the expression is false no matter what y is).

更多推荐

处理可能为无的变量

本文发布于:2023-10-22 22:15:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1518883.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能为   变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!