x或y:可接受的成语,或混淆?

编程入门 行业动态 更新时间:2024-10-13 02:20:35
本文介绍了x或y:可接受的成语,或混淆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我必须从一个变量中提取值,该变量可能是None,记住一些默认值。我第一次写下代码:

I have to extract values from a variable that may be None, with some defaults in mind. I first wrote this code:

if self.maxTiles is None: maxX, maxY = 2, 2 else: maxX, maxY = self.maxTiles

然后我意识到我可以缩短它:

Then I realized I could shorten it to:

maxX, maxY = self.maxTiles if self.maxTiles is not None else (2, 2)

但是我意识到这可能是最简洁和容易阅读的:

But then I realized this might be the most succinct and easily readable:

maxX, maxY = self.maxTiles or (2, 2)

推荐答案

关于,具体来说,

self.maxTiles if self.maxTiles is not None else (2, 2)

我发现一般形式的双重否定如果不是A:B else:C 语句或表达式)可能相当混乱/误导;这不是字面上的如果没有... else ,但移动不是不会使双负

I've found that "double negatives" of the general form if not A: B else: C (whether as statements or expressions) can be quite confusing / misleading; this isn't literally an if not .. else, but moving the not doesn't make the "double negative" go away.

因此,一般来说,如果A:C else:B 。在这种特殊情况下,如果我选择三元运算符形式,我将它编码为

So, in general, I just rewrite such constructs to if A: C else: B. In this particular case, if I did choose the ternary-operator form, I'd code it as

(2, 2) if self.maxTiles is None else self.maxTiles

对于更一般的问题: a = b或c 很好当且仅当你真的想使用 c b 的任何假值 c> 无。 IOW, b或c 是更好的表达方式。

On to the more general question: a = b or c is fine if and only if you really want to use c for any false value of b -- it's not fine to deal specifically with b being None. IOW, b or c is a better way to express

b if b else c

但是不是核心测试是, b是None 。在理论上,如果你知道 b 的唯一可能的假值是 None ,它们在语义上是等价的,但是强的只有可能的假值约束对你的代码的读者/维护者不会是明显的 - 如果你必须添加一个注释来解释,任何简单的优点或可能声明被废除...更好的是,如果可行,在代码中说,而不是让代码是晦涩的,需要评论,以澄清什么它在做什么和什么时候(意见,真正有用的是那些解释,而不是什么和什么时候[[代码本身应该显示!)]],而是为什么当它不明显 - 这个特定的应用程序目的是什么代码功能的tidbit)。

but it's not a way to express a similar expression where the core test is, instead, b is None. In theory, if you "know" that the only possible false value for b is None, they're semantically equivalent, but that strong "only possible false value" constraint will not be apparent to readers / maintainers of your code -- and if you have to add a comment to explain that, any conciseness advantages that or might claim are nullified... better, when feasible, to "say it in code", rather than have the code be obscure and need comments to clarify exactly what it's doing and when (comments that are really useful are rather those which explain, not the what and the when [[the code itself should show that!-)]], but rather the why when it's not obvious -- what's the application purpose being served by this specific tidbit of code functionality).

更多推荐

x或y:可接受的成语,或混淆?

本文发布于:2023-11-22 01:47:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615500.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成语   可接受

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!