Python默认值,并根据其他变量设置该值。到,否则。 [英] Python default values and setting the value based on other variables. To if else or to not.

查看:132
本文介绍了Python默认值,并根据其他变量设置该值。到,否则。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我有一个变量想要默认为某个变量,如果设置了其他变量,请将其更改为其他变量。

At times I have a variable that I want to default to something and if something else is set change it to something else.

问题是。什么是首选?设置默认值,然后在满足条件的情况下更改默认值,或者仅设置一次条件,具体取决于初始检查并添加其他内容?

The question is. What is preferred? Setting the default value and then changing it if the condition is met or setting the condition only once depending on the initial check with an added else?

代码示例。

if x:
    y = '%s-other' % x
else:
    y = 'some_default'

另一种选择是。

y = 'some_default'
if x:
    y = '%s-other' % x

这并不总是传递给函数的参数,因此kwargs并不是我要依赖的东西。

This isn't always an argument passed in to a function so kwargs is not something I want to rely on here.

就我个人而言,第二个似乎更清楚,但是我还没有找到任何人对此发表意见。

Personally, the second one seems to be a lot more clear to me but what I have yet to find any sort of opinion by anyone on this.

推荐答案

如何解决:

y = '%s-other' % x if x else 'some_default'

这篇关于Python默认值,并根据其他变量设置该值。到,否则。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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