姜戈:"%"在self.success_messages%fiche.__dict__中是什么意思



自从我学习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和在我的消息success中,我检索到fice.ref_id%(ref_id(s

%运算符是一个旧的字符串格式占位符,它允许您在字符串中包含变量。因此,如果您希望在字符串中包含变量name,则可以使用%运算符作为占位符。

name = 'world'
print('Hello, %s' % name)
>>> Hello, world

在您的示例中,success_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字符串,这使它更可读:

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字符串格式的

最新更新