I want to return an object’s property value from a function but I don’t know how to pass the property reference to the function
class my_class:
my_property = 0
c = my_class()
print (c.my_property)
def property_value(o, p):
return o.p
my_property = 'my_property'
print (property_value(c, my_property))
0
Traceback (most recent call last):
File "d:\teste.py", line 11, in <module>
print (property_value(c, my_property))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "d:\teste.py", line 8, in property_value
return o.p
^^^
AttributeError: 'my_class' object has no attribute 'p'
Tried to search but I can’t find the terms
>Solution :
You can use the builtin getattr() function for this
def property_value(o, p):
return getattr(o, str(p))
# NOTE: I'm using 'str(p)' here because the property name must be a string!
Then you’d call it just as before:
print(property_value(c, my_property))
# => 0
That said, there’s really no need to define a function like property_value here because getattr() already exists and does exactly the same thing!