[英]What is the best way to set a fallback value in Python?
我最近發現自己使用了以下模式:
x = 3
if this:
this.process()
if this.something:
x = this.a_value
我不想這樣做:
if this and (this.process() or True) and this.someting:
x = this.a_value
else:
x = 3
或這個:
if this:
this.process()
if this.something:
x = this.a_value
else:
x = 3
else:
x = 3
但我不禁覺得設置值然后改變它有點亂,特別是考慮到在某些用例中很少使用回退值。
有更好/更整潔的方式嗎?
我想到你提出的三個選項,第一個,即你正在使用的那個,是最好的。 代碼很清楚,每個人都會知道發生了什么。 我想不出更整潔/更整潔的方式,這就是我根據“簡單比復雜更好”編碼的方式。 原理
重新“ 我不禁覺得設置值然后改變它有點亂, ”如果你想要一個默認值,就沒辦法設置一個。
這當然是比使用其他兩個更為整潔else
辦法。 可讀性很重要。
從代碼維護的角度來看,我會接受第一個或第二個案例,但不會因為重復而接受第三個案例。
PS:在Python中,我通常希望看到self
來引用類實例對象,而不是this
。 最好不要將其用於this
目的或任何其他目的,以避免混淆。
不必更改值的最直接的方法是:
processed = False
if this:
this.process()
if this.something:
x = this.a_value
processed = True
if not processed:
x = 3
但是你要引入另一個變量。 如果您的默認值很容易計算,我只需將x
設置為3
。 應該理解,這是默認值。 如果計算的默認值很耗時,那么我會做另外的布爾選項。
我會有this.proccess()
返回this
並做
try: x = this.avalue if this.process() and this.something else 3
except AttributeError: x = 3;
即使裸體除了不是很棒(取決於過程的復雜性)
[編輯]第二個例子不會工作,所以我把它拿出來
這將避免首先設置默認值,而不重復:
def noncefunc(default):
if this:
this.process()
if this.something: return this.a_value
return default
x = noncefunc(3)
然而,這並不是特別清楚,當然也不是你所擁有的進步。 如果你想做這樣的事情,你最好使用一種語言,通過設計更自然地支持功能風格。 如果python是那種語言會很好,但遺憾的是它不是。
或者:
class breakexception(exception):pass
try:
if this:
this.process()
if this.something:
x = this.a_value
raise breakexception()
except breakexception: pass
else: x = 3
同樣,如果未首先設置非默認值,則僅設置默認值,但不容易理解。
最后:
if this:
this.process()
if this.something:
x = this.a_value
try: x = x
except UnboundLocalError: x = 3
這可能是您所擁有的替代方案中最清晰的,但它並不代表您對原始形式的進步。
堅持你所擁有的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.