簡體   English   中英

Python相當於C#6中引入的空條件運算符

[英]Python's equivalent to null-conditional operator introduced in C# 6

Python中是否存在與C# null-conditional運算符相當的?

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'>

那么,最簡​​單的解決方案是:

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')()

在這里,權衡是調用開銷的函數,但更清晰的代碼,特別是如果你多次使用它。

PEP-505下有一個提案,同時有一個圖書館:

from pymaybe import maybe

print(maybe(None).toString())

我用你需要的行為編寫了這個函數。 這種過度鏈的優勢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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM