python - if exists else 的简短写法

标签 python expression default

我想做的是:

if myObject:  # (not None)
    attr = myObject.someAttr
else:
    attr = ''

并尽可能避免使用三元表达式。有没有类似的东西:

attr = myObject.someAttr || '' ? 

我正在考虑创建自己的函数,例如:

get_attr_or_default(instance,attr,default):
    if instance:
        return instance.get_attribute(attr)
    else:
        return default

但是听到 python 没有这方面的快捷方式,我会感到很惊讶。

综合:

我尝试了两种解决方案,结果如下:

class myClass(Models.model):
    myObject = model.foreignKey('AnotherClass')

class AnotherClass(Models.model):
    attribute = models.charField(max_length=100,default = '')


attr = myClass.myObject.attribute if myClass.myObject else '' # WORKED
attr = myClass.myObject and myClass.myObject.attribute # WORKED with NONE as result
attr = myClass.myObject.attribute or ''  # Raises an error (myObject doesn't have attribute attribute)
try: attr = myClass.myObject.attribute
except AttributeError: attr = ''  # Worked

感谢您的回答!

最佳答案

6.11. Conditional expressions

attr = myObject.someAttr if myObject else ""

关于python - if exists else 的简短写法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22983066/

相关文章:

python - 任务列表输出

java - 我的表达是非法的,我不知道为什么

C# 浮点表达式 : strange behavior when casting the result float to int

android - 默认 SharedPreferences 不保存值

css - 删除空白区域是 SELECT angular app IE-CSS

python - 我可以从我的 Python 代码打开多个网络命名空间中的套接字吗?

python - 狮身人面像 : link to an internal file declared as html_extra_path

python - 如何正确复制嵌套的字典对象?

regex - 如何构建正则表达式来解析逗号分隔值但忽略双引号中的逗号?

android - 三星Touchwiz始终在Android 4.1.1中启动时提示默认应用程序