由于我一直在學習 Python,所以我經常看到和使用:
class FicheDeleteView(LoginRequiredMixin, DeleteView):
model = Fiche
success_url = reverse_lazy('fiche-list')
success_messages = "La Fiche %(ref_id)s a bien été supprimée"
def delete(self, request, *args, **kwargs):
fiche = self.get_object()
messages.success(self.request, self.success_messages %
fiche.__dict__)
return super(FicheDeleteView, self).delete(request, *args, **kwargs)
即使我看到了這個機制的效果,我也不確定是否能理解。
這是否意味著:我將所有 FICHE dict 發送到“reverse-lazy”,并在我的message.success中使用%(ref_id)s檢索fiche.ref_id?
uj5u.com熱心網友回復:
運算子是一個舊的%字串格式化占位符,它允許您在字串中包含變數。因此,如果您想name在字串中包含變數,則可以使用%運算子作為占位符。
name = 'world'
print('Hello, %s' % name)
>>> Hello, world
在您的示例中,%運算子 insuccess_message將字典作為變數,然后從ref_id該字典中的鍵訪問值。
success_messages = "La Fiche %(ref_id)s a bien été supprimée"
example_dict = {'key_1': 'value_1', 'ref_id': 'value_2'}
print(success_messages % example_dict)
>>> La Fiche value_2 a bien été supprimée
從 Python >= 3.6 開始,您可以使用f-strings使其更具可讀性:
example_dict = {'key_1': 'value_1', 'ref_id': 'value_2'}
print(f"La Fiche {example_dict['ref_id']} a bien été supprimée")
>>> La Fiche value_2 a bien été supprimée
您可以在此處閱讀有關 python 字串格式的更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438559.html
