本文介绍了Python等效于C#6中引入的空条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python中是否有等效于C#的空条件运算符?
Is there an equivalent in Python to C# null-conditional operator?
System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error
推荐答案
怎么样:
s = sb and sb.ToString()
如果sb为Falsy,则短路布尔值停止,否则返回下一个表达式.
The short circuited Boolean stops if sb is Falsy, else returns the next expression.
顺便说一句,如果获取None不重要...
Btw, if getting None is important...
sb = ""
#we wont proceed to sb.toString, but the OR will return None here...
s = (sb or None) and sb.toString()
print s, type(s)
输出:
None <type 'NoneType'>
这篇关于Python等效于C#6中引入的空条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!