gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:47 30 4
gpt4 key购买 nike

我有两个类(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.

关于Python getattr() 以另一个属性作为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31443989/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com