1

我一直在使用这种低效的风格在 Python 中进行编码

    checkbox = self.request.get(u'checkbox') # get data from a web form
    if checkbox == u'yes':
        someclass.enabled = True
    else:
        someclass.enabled = False

我该如何缩短这个?

4

9 回答 9

10
someclass.enabled = self.request.get(u'checkbox') == u'yes'
于 2012-09-04T01:40:12.510 回答
4

您可以在没有if声明的情况下执行此操作:

someclass.enabled = (checkbox == u'yes')

于 2012-09-04T01:40:56.597 回答
2

您可以将值设置为语句的结果:

checkbox = self.request.get(u'checkbox') # get data from a web form
someclass.enabled = checkbox == u'yes'
于 2012-09-04T01:41:02.010 回答
2

作为checkbox == u'yes'返回一个布尔值,您可以简单地将此结果直接分配给变量。

someclass.enabled = (checkbox == u'yes')
于 2012-09-04T01:42:22.550 回答
1

也许您可以将其拆分为不同的功能:

def getCheckboxValue(name):
    return (self.request.get(name) == u'yes')
于 2012-09-04T01:40:43.560 回答
1

Python 评估语句并将输出返回给语句。因此,您可以使用右侧的分配变量。

variable = eval_statment

所以你的例子将是

someclass.enabled = self.request.get(u'checkbox') == u'yes'
于 2012-09-04T02:57:19.583 回答
1

有点不清楚您是否在示例中使用了布尔值,因为它们是您的问题所固有的,还是因为它们是一个方便的示例。如果您想为变量分配比布尔值更复杂的类型,您可能还需要查看 Python 的三元运算符(如果您使用的是 2.5 或更高版本):

someclass.int_val = 1 if checkbox == u'yes' else 2

这转化为

if checkbox == u'yes':
    someclass.int_val = 1
else
    someclass.int_val = 2

对于布尔变量,我建议使用 Yuushi 的解决方案,但为了完整起见,它是这样的:

someclass.enabled = True if checkbox == u'yes' else False

它的打字量大致相同,但节省了一些垂直空间,这可能很有用。

于 2012-09-04T05:21:05.730 回答
0

如果您需要的不仅仅是一个布尔值,您应该考虑使用调度模式:

targets = {
  'yes': do_yes,
  'no': do_no,
  'maybe': do_maybe,
}

targets[self.request.get(u'tricheckbox')]()

# where do_yes, do_no, and do_maybe are the functions to call for each state.
于 2012-09-04T03:25:54.543 回答
-1

As pointed-out in another answer you could use dispatch table to do different things based on a value. However using a dictionary's get() method rather than \performing a direct lookup would allow you to also easily handle cases where nothing matches. Since the mapping won't be used again it can be temporary and anonymous.

This approach is very generic and can expanded as necessary, but usually requires extra functions to be written. Because of the latter, for very simple cases like your example, one of the other answers would probably require the least effort.

def do_yes(): print 'do_yes'
def do_no(): print 'do_no'
def do_maybe(): print 'do_maybe'
def no_match(): print 'no_match'

{
  u'yes': do_yes,
  u'no': do_no,
  u'maybe': do_maybe,
}.get(self.request.get(u'checkbox'), no_match) ()
于 2012-09-04T08:26:21.590 回答