我希望你能帮我做的是:
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
感谢您的回答!
bool(myObject)
可能会评估为False
,即使myObject is not None
- 空字符串/列表/元组/字典/集合、数值零(int/float等)和相当多的其他非内置类型在布尔上下文中具有false值。 - bruno desthuilliers