我有一个长代码,如下所示:
def to_representation(self, instance):
res = super().to_representation(instance)
res['receiver_phone_num'] = get_encryption_phone_num(instance.receiver_phone_num) if instance.receiver_phone_num else None
return res
第三行太长了,我很难在哪里休息一下,开始一行新的代码,这样可以使代码更可读、更清晰。
我试过这个:
res['receiver_phone_num'] = get_encryption_phone_num(
instance.receiver_phone_num
) if instance.receiver_phone_num else None
和
res['receiver_phone_num'] = get_encryption_phone_num(instance.receiver_phone_num)
if instance.receiver_phone_num else None
和
res['receiver_phone_num'] = get_encryption_phone_num(
instance.receiver_phone_num) if instance.receiver_phone_num else None
我更喜欢第一种换行的风格。你喜欢哪一种,或者你有其他看起来清晰漂亮的断线款式吗,请给我看看。
由于get_encryption_phone_num(instance.receiver_phone_num)
行在表达式中占用了大量空间,为了可读性,最好将其值分配给另一个变量,然后在表达式中使用该变量。
encryption_phone_num = get_encryption_phone_num(instance.receiver_phone_num)
就表达式的缩进而言,可以使用以下任意一种:
res['receiver_phone_num'] = (encryption_phone_num
if instance.receiver_phone_num
else None)
或
res['receiver_phone_num'] = (
encryption_phone_num
if instance.receiver_phone_num
else None
)