Python string to attribute

PythonAttributes

Python Problem Overview


How can I achieve such job:

def get_foo(someobject, foostring):
    return someobject.foostring

IE:

if I do get_foo(obj, "name") it should be calling obj.name (see input as string but I call it as an attritube.

Thanks

Python Solutions


Solution 1 - Python

Use the builtin function getattr.

> getattr(object, name[, default]) > > Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Solution 2 - Python

If someobject has an attribute named foostring then

def get_foo(someobject, foostring):
    return getattr(someobject,foostring)

or if you want to set an attribute to the supplied object then:

def set_foo(someobject, foostring, value):
    return setattr(someobject,foostring, value)

Try it

Solution 3 - Python

You should use setattr and getattr:

setattr(object,'property',value)
getattr(object,'property',default)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHellnarView Question on Stackoverflow
Solution 1 - PythonadamkView Answer on Stackoverflow
Solution 2 - PythonNazmul HasanView Answer on Stackoverflow
Solution 3 - PythonFrost.bakaView Answer on Stackoverflow