Python';s等价于C#6中引入的空条件运算符
Python中是否有与C#等价的语言Python';s等价于C#6中引入的空条件运算符,c#,python,C#,Python,Python中是否有与C#等价的语言 最简单的解决办法是: result = None if obj is None else obj.method() obj = 'hello' temp = obj result = None if temp is None else temp.split() 但是,如果您希望完全等效的函数具有与C#的Null条件运算符相同的线程安全性,那么它应该是: result = None if obj is None else obj.method() ob
最简单的解决办法是:
result = None if obj is None else obj.method()
obj = 'hello'
temp = obj
result = None if temp is None else temp.split()
但是,如果您希望完全等效的函数具有与C#的Null条件运算符相同的线程安全性,那么它应该是:
result = None if obj is None else obj.method()
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')()
在这里,折衷是函数调用开销,但代码要清晰得多,特别是如果您多次使用它。如何:
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'>
无
我使用您所需的行为编写了此函数。与链接和相比,这种方法的一个优点是,当涉及到长链时,更容易编写。请注意,这不适用于对象关键点,仅适用于属性
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
有一个提议,同时有一个图书馆:
from pymaybe import maybe
print(maybe(None).toString())
谢谢你,我知道这个方法,但我希望有一个更短的方法来做到这一点。不幸的是,没有。不过,如果您不介意开销的话,可以将其包装到函数中。我认为这个答案中的示例需要一些修改,因为它需要额外的上下文-Python没有内置的ToString
方法;为什么我们需要额外的步骤来处理temp=sb
;我将对其进行编辑以使其更合理。需要额外的步骤temp=sb
,因为空条件运算符就是这样工作的。如果我们做None如果sb不是其他人sb.ToString()
,它就不是线程安全的,因为sb引用可以在两次引用期间更改。@Python中的Tanmay多线程还不太常见,因此不值得关注,因为直到Python 2“线程”在独立进程中运行,现代Python多线程是围绕未来构建的,它们也没有共享状态。在大多数Python代码中,方法的线程安全不是一个问题。谢谢,如果没有其他问题,我会在一段时间后接受这个答案。如果sb不是None
,而是一个错误,那么这个解决方案会产生意想不到的结果。例如,如果sb=“”
,则给出的是“
”,而不是”。method()
,这对于以可读性为优先级的语言来说是可怕的。@lispguy它回答了这个问题,并演示了布尔短路的一些行为。但是,不,因为不明显,我自己不会用它。我有过这样的情况:我有一个变异函数fn
,但只是有时候,所以试着写fn和fn(x)
。因为这在你写它5分钟后就没有意义了,所以回到如果fn:fn(x)
谢谢你的推荐,@JLPeyret!这回答了你的问题吗?