How can I return a default value for an attribute?

2019-02-04 01:59发布

This question already has an answer here:

I have an object myobject, which might return None. If it returns None, it won't return an attribute id:

a = myobject.id

So when myobject is None, the stament above results in a AttributeError:

AttributeError: 'NoneType' object has no attribute 'id'

If myobject is None, then I want a to be equal to None. How do I avoid this exception in one line statement, such as:

a = default(myobject.id, None)

7条回答
神经病院院长
2楼-- · 2019-02-04 02:48
a=myobect.id if myobject else None
查看更多
登录 后发表回答