繁体   English   中英

在Python中设置回退值的最佳方法是什么?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM