3

我最近发现自己经常使用以下模式:

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

但是我不禁觉得设置值然后更改它有点混乱,特别是考虑到在某些用例中很少使用后备值。

有没有更好/更整洁的方法?

4

5 回答 5

3

我认为您提出的三个选项,第一个,即您正在使用的选项是最好的。代码很清晰,每个人都会知道发生了什么。我想不出更整洁/更整洁的方式,这也是我编码的方式,基于“简单胜于复杂”。原则

回复“我不禁觉得设置值然后更改它有点乱, ”如果你想要一个默认值,没有办法设置一个。

它肯定比使用其他两种else方法更整洁。可读性很重要。

于 2012-08-31T03:23:57.267 回答
1

不必更改值的最直接方法是:

processed = False
if this:
   this.process()
   if this.something:
       x = this.a_value
       processed = True
if not processed:
    x = 3

但是随后您将引入另一个变量。如果您的默认值易于计算,我将设置x3顶部。可以理解,这是默认值。如果默认值计算起来很耗时,那么我会做额外的布尔选项。

于 2012-08-31T03:56:39.113 回答
1

从代码维护的角度来看,我会接受第一种或第二种情况,但由于重复,我不会接受第三种情况。

PS:在 Python 中,我通常希望看到self引用类实例对象,而不是this. 最好不要this用于该目的或任何其他目的,以避免混淆。

于 2012-08-31T03:24:57.237 回答
0

我会this.proccess()回来this

 try: x = this.avalue if this.process() and this.something else 3
 except AttributeError: x = 3;

即使一个赤裸的除了不是真棒(取决于过程的复杂性)

[编辑]第二个例子不起作用所以我把它拿出来

于 2012-08-31T03:44:45.123 回答
0

这将避免先设置默认值,而无需重复:

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

这可能是您所拥有的替代方案中最清晰的,但它并不能真正代表您对原始形式的很大进步。

坚持你所拥有的。

于 2012-08-31T04:09:24.100 回答