如果存在els,写入的快捷方式

2024-06-08 05:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是:

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

尽可能避免三元表达式。是否有类似于:

^{pr2}$

我在考虑创建自己的功能,例如:

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

谢谢你的回答!在


Tags: orinstancedefaultgetmodelreturnifmodels
3条回答

如果myObjectNone,则将attr设置为None,如果{}是一个正确的对象,则将attr设置为None。在

attr = myObject and myObject.someAttr

只有在值需要时才执行右侧的求值,请参见Python Docs,其中说明:

In the case of and, if the left-hand side is equivalent to False, the right-hand side is not evaluated, and the left-hand value is returned.

这与C具有的??null coasecing运算符相同,请参见http://msdn.microsoft.com/en-us/library/ms173224.aspx。在

请注意,如果对象上有一个布尔运算符,这将不能很好地工作。如果是这样,则需要使用myObject is not None。在

很酷的方式(偶数不带三元表达式):

attr = getattr(myObject or object(), 'someAttr', '')

^{}返回一个新的无功能对象(引用文档)。在

如果myObject为空,myObject or object()将返回{}。在

逻辑: 在

^{pr2}$

6.11. Conditional expressions

attr = myObject.someAttr if myObject else ""

相关问题 更多 >

    热门问题