python 中 `get or default` 的通用方法是什么?

What is universal method for `get or default` in python?

我想获取 mongo 引擎模型对象的属性,但它丢失了(它在 mongo 中的常见情况):

unit.city 给我 AttributeError

unit.get('city')'Unit' object has no attribute 'get' 而我无法通过 dir(unit).

找到任何合适的方法

所以我必须使用标准 python 语句:

city = unit.city if 'city' in unit else None

这对于 get 操作来说有点复杂,因为我有很多这种类型的转换。

所以我想知道是否有任何通用方法来获取属性值或某些默认值(如果属性不存在)——例如 get 用于 dict 类型:

city = unit.get('city') # None
# or
city = unit.get('city', 'Moscow') # 'Moscow'

我会定义自己的函数 get 但我对标准库中是否有函数感兴趣。然而,from operation import getitem 做不到。

我用的是python2,顺便说一句。

getattr(object, name[, default]):

city = getattr(unit, 'city', 'Moscow')

一般来说python,有两种常见的模式。 hasattr + getattr 的混合或将整个事物包装在 try / except

city = getattr(unit,'city','Moscow')

另一种方法是

try:
    city = unit.city
except AttributeError:
    city = None

第二个可以说更 pythonic。但是,当您处理数据库时。最好使用 ORM 并一起避免这种事情。