Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method on getattr() function

I use python-metar to decode METAR data. Object returned after parsing METAR strings looks like this:

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

These attributes, have additional methods - value(), unit(), and string(). I used the getattr() builtin function to loop over all of them:

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

But this way I get the default string representation, and that is a string with a value and its unit, like 10 knots, while I'd like to get just the numerical value, which I can reach through value() method:

>>> decoded.wind_speed.value()
10.0

So I can't figure how to use getattr() and at the same time to call a method (in this case value() method).

like image 872
vedar Avatar asked May 21 '26 00:05

vedar


1 Answers

With your code, getattr will return till decoded.wind_speed. If you want to call value function of decoded.wind_speed you have to call value() with the object return by getattr.

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

OR

You can use another getattr to call value method.

print(getattr(getattr(decoded, attr)), "value")()
like image 106
Nilesh Avatar answered May 22 '26 14:05

Nilesh