Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass an object property reference to a functon

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading