Python条件赋值运算符 [英] Python conditional assignment operator

查看:92
本文介绍了Python条件赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在与Ruby || = 运算符等效的Python(如果未设置变量则设置变量)?

Does a Python equivalent to the Ruby ||= operator ("set the variable if the variable is not set") exist?

Ruby中的示例:

 variable_not_set ||= 'bla bla'
 variable_not_set == 'bla bla'

 variable_set = 'pi pi'
 variable_set ||= 'bla bla'
 variable_set == 'pi pi'


推荐答案

否,替换为:

try:
   v
except NameError:
   v = 'bla bla'

但是,想要使用此结构表明代码流过于复杂。通常,您会执行以下操作:

However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following:

try:
   v = complicated()
except ComplicatedError: # complicated failed
   v = 'fallback value'

,并且永远不能确定 v 是否已设置。如果它是可以设置或无法设置的众多选项之一,请使用字典及其 get 方法可使用默认值。

and never be unsure whether v is set or not. If it's one of many options that can either be set or not, use a dictionary and its get method which allows a default value.

这篇关于Python条件赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆