用布尔表达式分配字符串

用布尔表达式分配字符串

本文介绍了用布尔表达式分配字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从别人的项目中理解这段代码.如果你想要上下文,它在这里:https://github.com/newsapps/beeswithmachineguns/blob/master/beeswithmachineguns/bees.py#L501

IS_PY2 只是一个布尔变量,True 如果 Python 主要版本是 2.我知道一个非空字符串是 True,但由于某种原因我不明白 openmode 被分配了 'w''wt' 而不是 TrueFalse.

openmode = IS_PY2 和 'w' 或 'wt'openkwargs = IS_PY2 和 {} 或 {'encoding': 'utf-8', 'newline': ''}

有人能解释一下结果吗?

解决方案

三元布尔表达式的作用如下:

>>>2 和 3 或 43>>>0 和 3 或 44

所以,这个表达式:

openmode = IS_PY2 和 'w' 或 'wt'

使用 Python 2:

openmode = True 和 'w' 或 'wt'

相当于

openmode = 'w' 或 'wt'

所以,我给出了 w.

在 Python 3 下,IS_PY2 为 False,给出:

openmode = False 和 'w' 或 'wt'

相当于

openmode = False 或 'wt'

给予wt.

这一切都是为了明确说明openmode是针对文本文件的,而不是二进制的,Python2中用w表示,Python3中用wt表示.

虽然 Python3 t 模式是默认模式,但没有必要精确.

参见这个关于wt模式的答案.

最后,我认为以下内容更具可读性:

openmode = 'w' if IS_PY2 else 'wt'

还有这个,更简单:

openmode = 'w'

I am trying to understand this code from someone else's project. If you want the context it's here: https://github.com/newsapps/beeswithmachineguns/blob/master/beeswithmachineguns/bees.py#L501

IS_PY2 is just a boolean variable, True if the Python major version is 2.I know that a non-empty string is True, but for some reason I don't understand openmode is assigned either 'w' or 'wt' rather than True or False.

openmode = IS_PY2 and 'w' or 'wt'
openkwargs = IS_PY2 and {} or {'encoding': 'utf-8', 'newline': ''}

Could someone explain the result?

解决方案

The ternary boolean expression works as:

>>> 2 and 3 or 4
3
>>> 0 and 3 or 4
4

So, this expression:

openmode = IS_PY2 and 'w' or 'wt'

Become in Python 2:

openmode = True and 'w' or 'wt'

Which is equivalent to

openmode = 'w' or 'wt'

So, i gives w.

Under Python 3, IS_PY2 is False, giving:

openmode = False and 'w' or 'wt'

Which is equivalent to

openmode = False or 'wt'

Giving wt.


All of this is to specify explicitely that the openmode is for text files, not binary, which is indicated by w in Python2 and wt in Python3.

While the Python3 t mode is the default one, this is not necessary to precise it.

See this answer about wt mode.


Finally, i think that the following is much more readable:

openmode = 'w' if IS_PY2 else 'wt'

And this one, much more simple:

openmode = 'w'

这篇关于用布尔表达式分配字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 20:10