90

This code doesn't work:

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

I want to make it so that if I call get_foo(obj, "name"), I get obj.name returned. How can I make that work?

0

3 Answers 3

127

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.

Sign up to request clarification or add additional context in comments.

1 Comment

that's a huge blessing that we can do that =)
54

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

Comments

37

You should use setattr and getattr:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.