3

私は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 のままですか?

4

5 に答える 5

11

あなたの質問に答える:

ブール値はPythonで変更可能ですか?

はいといいえ。ブール値が割り当てられた変数は (おそらく常に、この場合は間違いなく) 変更可能です。はい。変数は静的に型付けされていないため、ブール値が割り当てられることに制限されていません。

ただし、ブール値TrueFalseそれ自体は可変ではありません。それらは変更できないシングルトンです。

あなたの実際のコードを見る:

if success = 1:

は有効な構文ではありません==。また、慣用的に言えば、0and1を使用すべきではなく、成功と失敗の値には and を使用する必要がTrueあり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')
于 2012-08-10T20:33:38.567 に答える
1

整数ではなく、実際のブール値の使用を検討する必要があります。orに設定successすると、Python はそれらを 1 と 0 の値のキーワードとして解釈します。数値の使用は、言語によって解釈が異なるため、少し注意が必要です。一部の言語では 0 ですが、0 以外の値はすべて考慮されます。ただし、あなたの質問に対する答えは「はい」です。問題なく動作します。truefalsefalsetrue

于 2012-08-10T20:36:48.523 に答える
1

はい。success成功すると 1 に変更されます。

于 2012-08-10T20:29:47.317 に答える
1

There are a few things wrong with this snippet.

  1. Firstly, you're not using a boolean type. Python's booleans are True and False.
  2. Second, you're not comparing in your if statement. That line isn't valid in Python 3. What you're looking for is: if success == 1: or if success == True:
  3. You would still be able to assign a boolean value to a variable regardless of boolean immutability. I believe they are stored as a primitive type, so they're as immutable as any other primitive type.
于 2012-08-10T20:34:20.070 に答える