Skip to main content
 首页 » 编程设计

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

2025年05月04日17xing901022

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

我有一个函数接受任一类作为参数。是否有一种单行方法可以将新变量分配给 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 >.

请您参考如下方法:

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

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

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