我一直在使用这种低效的风格在 Python 中进行编码
checkbox = self.request.get(u'checkbox') # get data from a web form
if checkbox == u'yes':
someclass.enabled = True
else:
someclass.enabled = False
我该如何缩短这个?
我一直在使用这种低效的风格在 Python 中进行编码
checkbox = self.request.get(u'checkbox') # get data from a web form
if checkbox == u'yes':
someclass.enabled = True
else:
someclass.enabled = False
我该如何缩短这个?
someclass.enabled = self.request.get(u'checkbox') == u'yes'
您可以在没有if
声明的情况下执行此操作:
someclass.enabled = (checkbox == u'yes')
您可以将值设置为语句的结果:
checkbox = self.request.get(u'checkbox') # get data from a web form
someclass.enabled = checkbox == u'yes'
作为checkbox == u'yes'
返回一个布尔值,您可以简单地将此结果直接分配给变量。
someclass.enabled = (checkbox == u'yes')
也许您可以将其拆分为不同的功能:
def getCheckboxValue(name):
return (self.request.get(name) == u'yes')
Python 评估语句并将输出返回给语句。因此,您可以使用右侧的分配变量。
像
variable = eval_statment
所以你的例子将是
someclass.enabled = self.request.get(u'checkbox') == u'yes'
有点不清楚您是否在示例中使用了布尔值,因为它们是您的问题所固有的,还是因为它们是一个方便的示例。如果您想为变量分配比布尔值更复杂的类型,您可能还需要查看 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
它的打字量大致相同,但节省了一些垂直空间,这可能很有用。
如果您需要的不仅仅是一个布尔值,您应该考虑使用调度模式:
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.
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) ()