是否有Python等效于C#null-coalescing运算符? [英] Is there a Python equivalent of the C# null-coalescing operator?

查看:137
本文介绍了是否有Python等效于C#null-coalescing运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,有一个空合并运算符(写为??),以便在分配过程中轻松进行(简短的)空检查:

In C# there's a null-coalescing operator (written as ??) that allows for easy (short) null checking during assignment:

string s = null;
var other = s ?? "some default value";

是否有python等效项?

Is there a python equivalent?

我知道我可以做到:

s = None
other = s if s else "some default value"

但是还有没有更短的方法(我不需要重复s)?

But is there an even shorter way (where I don't need to repeat s)?

推荐答案

other = s or "some default value"

好的,必须弄清楚or运算符的工作方式.它是一个布尔运算符,因此可以在布尔上下文中工作.如果这些值不是布尔值,则出于操作员的目的将其转换为布尔值.

Ok, it must be clarified how the or operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.

请注意,or运算符不会仅返回TrueFalse.相反,如果第一个操作数的计算结果为true,则返回第一个操作数;如果第一个操作数的计算结果为false,则返回第二个操作数.

Note that the or operator does not return only True or False. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.

在这种情况下,表达式x or y如果为True则返回x或在转换为布尔值时计算为true.否则,它返回y.在大多数情况下,这将与C♯的空值运算符相同,但请记住:

In this case, the expression x or y returns x if it is True or evaluates to true when converted to boolean. Otherwise, it returns y. For most cases, this will serve for the very same purpose of C♯'s null-coalescing operator, but keep in mind:

42    or "something"    # returns 42
0     or "something"    # returns "something"
None  or "something"    # returns "something"
False or "something"    # returns "something"
""    or "something"    # returns "something"

如果使用变量s来保存对类实例或None的引用(只要您的类未定义成员__nonzero__()__len__()),则为安全地使用与null-coalescing运算符相同的语义.

If you use your variable s to hold something that is either a reference to the instance of a class or None (as long as your class does not define members __nonzero__() and __len__()), it is secure to use the same semantics as the null-coalescing operator.

实际上,具有Python的这种副作用甚至可能是有用的.由于您知道哪些值的计算结果为false,因此可以使用它来触发默认值,而无需专门使用None(例如错误对象).

In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None specifically (an error object, for example).

在某些语言中,这种行为称为 Elvis运算符.

In some languages this behavior is referred to as the Elvis operator.

这篇关于是否有Python等效于C#null-coalescing运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆