问题描述
例如,在C#(从v6开始)中,我可以说:
For instance, in C# (starting with v6) I can say:
mass = (vehicle?.Mass / 10) ?? 150;
如果存在车辆,则将质量设置为车辆质量的十分之一,如果车辆为空(如果质量属性为可空类型,则为零),将质量设置为150.
to set mass to a tenth of the vehicle's mass if there is a vehicle, but 150 if the vehicle is null (or has a null mass, if the Mass property is of a nullable type).
我在C#应用程序的脚本中可以使用Python(特别是IronPython)中的等效结构吗?
Is there an equivalent construction in Python (specifically IronPython) that I can use in scripts for my C# app?
这对于显示可以被其他值修改的值的默认值特别有用-例如,我可能在脚本中为我的飞船定义了一个装甲组件,该组件总是消耗船上可用空间的10%安装在其上,其其他属性也可以缩放,但是我想显示装甲大小,生命值,成本等的默认值,以便您可以将其与其他舰船组件进行比较.否则,我可能不得不编写一个进行一两个空检查的卷积表达式,就像在v6之前的C#中一样.
This would be particularly useful for displaying defaults for values that can be modified by other values - for instance, I might have an armor component defined in script for my starship that is always consumes 10% of the space available on the ship it's installed on, and its other attributes scale as well, but I want to display defaults for the armor's size, hitpoints, cost, etc. so you can compare it with other ship components. Otherwise I might have to write a convoluted expression that does a null check or two, like I had to in C# before v6.
推荐答案
否,Python还没有NULL运算符.
No, Python does not (yet) have NULL-coalescing operators.
有一个建议( PEP 505 – 不知道的运算符 )来添加此类运算符,但是无论是否将这些运算符添加到语言中,都没有共识,如果是的话,它们将采用什么形式.
There is a proposal (PEP 505 – None-aware operators) to add such operators, but no consensus exists wether or not these should be added to the language at all and if so, what form these would take.
来自实施部分:
请注意,Python实际上并没有 null
的概念. Python名称和属性总是 引用 something ,它们从来都不是null
引用. None
只是Python中的另一个对象,社区不愿意使该对象如此特殊以至于需要它自己的运算符.
Note that Python doesn't really have a concept of null
. Python names and attributes always reference something, they are never a null
reference. None
is just another object in Python, and the community is reluctant to make that one object so special as to need its own operators.
直到实现该时间为止(如果有的话,IronPython会赶上该Python版本),您可以使用Python的实现相同的目的:
Until such time this gets implemented (if ever, and IronPython catches up to that Python release), you can use Python's conditional expression to achieve the same:
mass = 150 if vehicle is None or vehicle.Mass is None else vehicle.Mass / 10
这篇关于是否有等效于C#的Python?和 ??操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!