Python:如果不存在则赋值 [英] Python: Assign Value if None Exists

查看:99
本文介绍了Python:如果不存在则赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名刚接触 Python 的 RoR 程序员.我试图找到允许我将变量设置为特定值的语法,前提是它以前没有分配过.基本上我想要:

I am a RoR programmer new to Python. I am trying to find the syntax that will allow me to set a variable to a specific value only if it wasn't previously assigned. Basically I want:

# only if var1 has not been previously assigned

var1 = 4

推荐答案

这是一种非常不同的编程风格,但我总是尝试重写看起来像的东西

This is a very different style of programming, but I always try to rewrite things that looked like

bar = None
if foo():
    bar = "Baz"

if bar is None:
    bar = "Quux"

变成:

if foo():
    bar = "Baz"
else:
    bar = "Quux"

也就是说,我尽量避免出现某些代码路径定义变量而其他代码路径不定义的情况.在我的代码中,从来没有一条路径会导致定义变量集的歧义(事实上,我通常更进一步,确保类型是相同的,而不管代码路径如何).这可能只是个人品味的问题,但我发现这种模式虽然在我写的时候不那么明显,但当我以后阅读时更容易理解.

That is to say, I try hard to avoid a situation where some code paths define variables but others don't. In my code, there is never a path which causes an ambiguity of the set of defined variables (In fact, I usually take it a step further and make sure that the types are the same regardless of code path). It may just be a matter of personal taste, but I find this pattern, though a little less obvious when I'm writing it, much easier to understand when I'm later reading it.

这篇关于Python:如果不存在则赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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