Python getattr() 将另一个属性作为默认值

Python getattr() with another attribute as the default

我有两个 class。一个 class 具有属性 x 但没有 y,另一个 class 具有属性 y 但没有 x.

我有一个接受 class 作为参数的函数。是否有一种单行方法可以将新变量分配给 x 属性(如果存在)或 y 属性(如果不存在)?即,

if hasattr(input_object, 'x'):
    new_var = input_object.x
else:
    new_var = input_object.y

我以为我能做到:

new_var = getattr(input_object, 'x', input_object.y)

但是如果 input_object 没有 y,即使它有 x.

,也会引发 AttributeError

您可以使用 getattry 到。

new_var = getattr(input_object, 'x', None) or getattr(input_object, 'y', None)

或者您可以使用 if/else 结构:

new_var = (
  input_object.x if hasattr(input_object, 'x')
  else input_object.y
)

这不会评估input_object.y 除非没有 input_object.x.

像这样嵌套 getattr 调用:

getattr(model, "field1", getattr(model, "field2", None))