我在 python 中有以下代码:
def update(request, id):
success = 0
try:
product = Mattress.objects.get(id=id)
success = 1
except Mattress.DoesNotExist:
pass
if success == 1:
return render_to_response("success.html")
else:
return render_to_response('failure.html')
此代码是检查“成功”布尔值的有效方法吗?如果代码通过了try语句,“成功”会变成1还是保持为0?
回答你的问题:
python 中的布尔值是可变的吗?
是和不是。是的,分配了布尔值的变量(可能总是,并且在本例中肯定是)可变的。它们也不限于分配布尔值,因为变量不是静态类型的。
但是布尔值True
and False
它们本身是不可变的。它们是无法修改的单例。
查看您的实际代码:
if success = 1:
语法无效,您需要一个==
那里。另外,惯用的说法你不应该使用0
and 1
对于成功和失败值,您应该使用True
and False
。所以你应该重构为这样的:
def update(request):
success = False
try:
product = Mattress.objects.get(id=id)
success = True
except Mattress.DoesNotExist:
pass
if success:
return render_to_response("success.html")
else:
return render_to_response('failure.html')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)