gpt4 book ai didi

python - 在 getattr() 函数上调用方法

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:24 25 4
gpt4 key购买 nike

我使用 python-metar 解码 METAR数据。解析 METAR 字符串后返回的对象如下所示:

>>> dir(decoded)[-5:]
['wind_shift', 'wind_shift_time', 'wind_speed', 'wind_speed_peak', 'windshear']

这些属性有额外的方法 - value()unit()string()。我使用 getattr() 内置函数遍历所有这些函数:

>>> attributes = [..., 'wind_speed', 'wind_speed_peak', 'windshear']
>>> for attr in attributes:
>>> print(getattr(decoded, attr))

但是通过这种方式,我得到了默认的字符串表示形式,这是一个带有值及其单位的字符串,例如 10 knots,而我只想得到数值,我可以通过value()方法到达:

>>> decoded.wind_speed.value()
10.0

所以我不知道如何使用 getattr() 并同时调用方法(在本例中为 value() 方法)。

最佳答案

使用您的代码,getattr将返回到 decoded.wind_speed .如果您想调用value decoded.wind_speed的功能你必须调用value()对象返回 getattr .

print(getattr(decoded, attr).value())

您可以使用另一个 getattr调用value方法。

print(getattr(getattr(decoded, attr)), "value")()

关于python - 在 getattr() 函数上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35497920/

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