Python中是否有与C#相当的# 零条件运算符?
System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error
Python中是否有与C#相当的# 零条件运算符?
System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error
怎么样:
s = sb and sb.ToString()
如果sb是Falsy,则短路布尔值停止,否则返回下一个表达式。
顺便说一下,如果得到无则很重要......
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'>
怎么样:
s = sb and sb.ToString()
如果sb是Falsy,则短路布尔值停止,否则返回下一个表达式。
顺便说一下,如果得到无则很重要......
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'>
那么,最简单的解决方案是:
result = None if obj is None else obj.method()
但是如果你想要具有与C#的Null条件运算符相同的线程安全性的完全等价,那么它将是:
obj = 'hello'
temp = obj
result = None if temp is None else temp.split()
权衡的是代码不是很漂亮;还有一个额外的名字 temp
被添加到命名空间。
另一种方式是:
def getattr_safe(obj, attr):
return None if obj is None else getattr(obj,attr)
obj = 'hello'
result = getattr_safe(obj,'split')()
在这里,权衡是调用开销的函数,但更清晰的代码,特别是如果你多次使用它。
我用你需要的行为编写了这个函数。这种优势超链接 and
就长链而言,它更容易编写。抬头这不适用于对象键,只有属性。
def null_conditional(start, *chain):
current = start
for c in chain:
current = getattr(current, c, None)
if current is None:
break
return current
这是我运行的一些测试,所以你可以看到它是如何工作的
class A(object):
b = None
def __init__(self, v):
self.b = v
class B(object):
c = None
def __init__(self, v):
self.c = v
a_1 = A(B(2))
a_2 = A(None)
print(null_conditional(a_1, 'b', 'c')) # 2
print(null_conditional(a_1, 'b', 'd')) # None
print(null_conditional(a_2, 'b', 'c')) # None
print(null_conditional(None, 'b')) # None
print(null_conditional(None, None)) # TypeError: attribute name must be string